2 * OOjs v1.0.12 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2014 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2014-08-20T22:33:41Z
11 ( function ( global
) {
15 /*exported toString */
18 * Namespace for all classes, static methods and static properties.
23 hasOwn
= oo
.hasOwnProperty
,
24 toString
= oo
.toString
;
29 * Utility to initialize a class for OO inheritance.
31 * Currently this just initializes an empty static object.
33 * @param {Function} fn
35 oo
.initClass = function ( fn
) {
36 fn
.static = fn
.static || {};
40 * Utility for common usage of Object#create for inheriting from one
41 * prototype to another.
43 * Beware: This redefines the prototype, call before setting your prototypes.
44 * Beware: This redefines the prototype, can only be called once on a function.
45 * If called multiple times on the same function, the previous prototype is lost.
46 * This is how prototypal inheritance works, it can only be one straight chain
47 * (just like classical inheritance in PHP for example). If you need to work with
48 * multiple constructors consider storing an instance of the other constructor in a
49 * property instead, or perhaps use a mixin (see OO.mixinClass).
52 * Thing.prototype.exists = function () {};
55 * Person.super.apply( this, arguments );
57 * OO.inheritClass( Person, Thing );
58 * Person.static.defaultEyeCount = 2;
59 * Person.prototype.walk = function () {};
62 * Jumper.super.apply( this, arguments );
64 * OO.inheritClass( Jumper, Person );
65 * Jumper.prototype.jump = function () {};
67 * Jumper.static.defaultEyeCount === 2;
68 * var x = new Jumper();
71 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
73 * @param {Function} targetFn
74 * @param {Function} originFn
75 * @throws {Error} If target already inherits from origin
77 oo
.inheritClass = function ( targetFn
, originFn
) {
78 if ( targetFn
.prototype instanceof originFn
) {
79 throw new Error( 'Target already inherits from origin' );
82 var targetConstructor
= targetFn
.prototype.constructor;
84 // Using ['super'] instead of .super because 'super' is not supported
85 // by IE 8 and below (bug 63303).
86 // Provide .parent as alias for code supporting older browsers which
87 // allows people to comply with their style guide.
88 targetFn
['super'] = targetFn
.parent
= originFn
;
90 targetFn
.prototype = Object
.create( originFn
.prototype, {
91 // Restore constructor property of targetFn
93 value
: targetConstructor
,
100 // Extend static properties - always initialize both sides
101 oo
.initClass( originFn
);
102 targetFn
.static = Object
.create( originFn
.static );
106 * Utility to copy over *own* prototype properties of a mixin.
107 * The 'constructor' (whether implicit or explicit) is not copied over.
109 * This does not create inheritance to the origin. If inheritance is needed
110 * use oo.inheritClass instead.
112 * Beware: This can redefine a prototype property, call before setting your prototypes.
113 * Beware: Don't call before oo.inheritClass.
116 * function Context() {}
118 * // Avoid repeating this code
119 * function ContextLazyLoad() {}
120 * ContextLazyLoad.prototype.getContext = function () {
121 * if ( !this.context ) {
122 * this.context = new Context();
124 * return this.context;
127 * function FooBar() {}
128 * OO.inheritClass( FooBar, Foo );
129 * OO.mixinClass( FooBar, ContextLazyLoad );
131 * @param {Function} targetFn
132 * @param {Function} originFn
134 oo
.mixinClass = function ( targetFn
, originFn
) {
137 // Copy prototype properties
138 for ( key
in originFn
.prototype ) {
139 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
140 targetFn
.prototype[key
] = originFn
.prototype[key
];
144 // Copy static properties - always initialize both sides
145 oo
.initClass( targetFn
);
146 if ( originFn
.static ) {
147 for ( key
in originFn
.static ) {
148 if ( hasOwn
.call( originFn
.static, key
) ) {
149 targetFn
.static[key
] = originFn
.static[key
];
153 oo
.initClass( originFn
);
160 * Create a new object that is an instance of the same
161 * constructor as the input, inherits from the same object
162 * and contains the same own properties.
164 * This makes a shallow non-recursive copy of own properties.
165 * To create a recursive copy of plain objects, use #copy.
167 * var foo = new Person( mom, dad );
169 * var foo2 = OO.cloneObject( foo );
173 * foo2 !== foo; // true
174 * foo2 instanceof Person; // true
175 * foo2.getAge(); // 21
176 * foo.getAge(); // 22
178 * @param {Object} origin
179 * @return {Object} Clone of origin
181 oo
.cloneObject = function ( origin
) {
184 r
= Object
.create( origin
.constructor.prototype );
186 for ( key
in origin
) {
187 if ( hasOwn
.call( origin
, key
) ) {
188 r
[key
] = origin
[key
];
196 * Get an array of all property values in an object.
198 * @param {Object} Object to get values from
199 * @return {Array} List of object values
201 oo
.getObjectValues = function ( obj
) {
204 if ( obj
!== Object( obj
) ) {
205 throw new TypeError( 'Called on non-object' );
210 if ( hasOwn
.call( obj
, key
) ) {
211 values
[values
.length
] = obj
[key
];
219 * Recursively compares properties between two objects.
221 * A false result may be caused by property inequality or by properties in one object missing from
222 * the other. An asymmetrical test may also be performed, which checks only that properties in the
223 * first object are present in the second object, but not the inverse.
225 * If either a or b is null or undefined it will be treated as an empty object.
227 * @param {Object|undefined} a First object to compare
228 * @param {Object|undefined} b Second object to compare
229 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
230 * @return {boolean} If the objects contain the same values as each other
232 oo
.compare = function ( a
, b
, asymmetrical
) {
233 var aValue
, bValue
, aType
, bType
, k
;
243 if ( !hasOwn
.call( a
, k
) ) {
244 // Support es3-shim: Without this filter, comparing [] to {} will be false in ES3
245 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
251 aType
= typeof aValue
;
252 bType
= typeof bValue
;
253 if ( aType
!== bType
||
254 ( ( aType
=== 'string' || aType
=== 'number' ) && aValue
!== bValue
) ||
255 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
259 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
260 return asymmetrical
? true : oo
.compare( b
, a
, true );
264 * Create a plain deep copy of any kind of object.
266 * Copies are deep, and will either be an object or an array depending on `source`.
268 * @param {Object} source Object to copy
269 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
270 * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the nodeCallback returns a value other than undefined, the returned value is used instead of attempting to clone.
271 * @return {Object} Copy of source object
273 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
274 var key
, destination
;
276 if ( nodeCallback
) {
277 // Extensibility: check before attempting to clone source.
278 destination
= nodeCallback( source
);
279 if ( destination
!== undefined ) {
284 if ( Array
.isArray( source
) ) {
285 // Array (fall through)
286 destination
= new Array( source
.length
);
287 } else if ( source
&& typeof source
.clone
=== 'function' ) {
288 // Duck type object with custom clone method
289 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
290 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
292 return leafCallback
?
293 leafCallback( source
.cloneNode( true ) ) :
294 source
.cloneNode( true );
295 } else if ( oo
.isPlainObject( source
) ) {
296 // Plain objects (fall through)
299 // Non-plain objects (incl. functions) and primitive values
300 return leafCallback
? leafCallback( source
) : source
;
303 // source is an array or a plain object
304 for ( key
in source
) {
305 destination
[key
] = oo
.copy( source
[key
], leafCallback
, nodeCallback
);
308 // This is an internal node, so we don't apply the leafCallback.
313 * Generate a hash of an object based on its name and data.
315 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
317 * To avoid two objects with the same values generating different hashes, we utilize the replacer
318 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
319 * not be the fastest way to do this; we should investigate this further.
321 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
322 * function, we call that function and use its return value rather than hashing the object
323 * ourselves. This allows classes to define custom hashing.
325 * @param {Object} val Object to generate hash for
326 * @return {string} Hash of object
328 oo
.getHash = function ( val
) {
329 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
333 * Helper function for OO.getHash which sorts objects by key.
335 * This is a callback passed into JSON.stringify.
337 * @method getHash_keySortReplacer
338 * @param {string} key Property name of value being replaced
339 * @param {Mixed} val Property value to replace
340 * @return {Mixed} Replacement value
342 oo
.getHash
.keySortReplacer = function ( key
, val
) {
343 var normalized
, keys
, i
, len
;
344 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
345 // This object has its own custom hash function, use it
346 val
= val
.getHashObject();
348 if ( !Array
.isArray( val
) && Object( val
) === val
) {
349 // Only normalize objects when the key-order is ambiguous
350 // (e.g. any object not an array).
352 keys
= Object
.keys( val
).sort();
355 for ( ; i
< len
; i
+= 1 ) {
356 normalized
[keys
[i
]] = val
[keys
[i
]];
360 // Primitive values and arrays get stable hashes
361 // by default. Lets those be stringified as-is.
368 * Compute the union (duplicate-free merge) of a set of arrays.
370 * Arrays values must be convertable to object keys (strings).
372 * By building an object (with the values for keys) in parallel with
373 * the array, a new item's existence in the union can be computed faster.
375 * @param {Array...} arrays Arrays to union
376 * @return {Array} Union of the arrays
378 oo
.simpleArrayUnion = function () {
379 var i
, ilen
, arr
, j
, jlen
,
383 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
385 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
386 if ( !obj
[ arr
[j
] ] ) {
387 obj
[ arr
[j
] ] = true;
388 result
.push( arr
[j
] );
397 * Combine arrays (intersection or difference).
399 * An intersection checks the item exists in 'b' while difference checks it doesn't.
401 * Arrays values must be convertable to object keys (strings).
403 * By building an object (with the values for keys) of 'b' we can
404 * compute the result faster.
407 * @param {Array} a First array
408 * @param {Array} b Second array
409 * @param {boolean} includeB Whether to items in 'b'
410 * @return {Array} Combination (intersection or difference) of arrays
412 function simpleArrayCombine( a
, b
, includeB
) {
417 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
421 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
422 isInB
= !!bObj
[ a
[i
] ];
423 if ( isInB
=== includeB
) {
432 * Compute the intersection of two arrays (items in both arrays).
434 * Arrays values must be convertable to object keys (strings).
436 * @param {Array} a First array
437 * @param {Array} b Second array
438 * @return {Array} Intersection of arrays
440 oo
.simpleArrayIntersection = function ( a
, b
) {
441 return simpleArrayCombine( a
, b
, true );
445 * Compute the difference of two arrays (items in 'a' but not 'b').
447 * Arrays values must be convertable to object keys (strings).
449 * @param {Array} a First array
450 * @param {Array} b Second array
451 * @return {Array} Intersection of arrays
453 oo
.simpleArrayDifference = function ( a
, b
) {
454 return simpleArrayCombine( a
, b
, false );
459 oo
.isPlainObject
= $.isPlainObject
;
464 * @class OO.EventEmitter
468 oo
.EventEmitter
= function OoEventEmitter() {
472 * Storage of bound event handlers by event name.
479 oo
.initClass( oo
.EventEmitter
);
484 * Add a listener to events of a specific event.
486 * The listener can be a function or the string name of a method; if the latter, then the
487 * name lookup happens at the time the listener is called.
489 * @param {string} event Type of event to listen to
490 * @param {Function|string} method Function or method name to call when event occurs
491 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
492 * @param {Object} [context=null] Context object for function or method call
493 * @throws {Error} Listener argument is not a function or a valid method name
496 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
499 this.constructor.static.validateMethod( method
, context
);
501 if ( hasOwn
.call( this.bindings
, event
) ) {
502 bindings
= this.bindings
[event
];
504 // Auto-initialize bindings list
505 bindings
= this.bindings
[event
] = [];
511 context
: ( arguments
.length
< 4 ) ? null : context
517 * Adds a one-time listener to a specific event.
519 * @param {string} event Type of event to listen to
520 * @param {Function} listener Listener to call when event occurs
523 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
524 var eventEmitter
= this,
525 listenerWrapper = function () {
526 eventEmitter
.off( event
, listenerWrapper
);
527 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
529 return this.on( event
, listenerWrapper
);
533 * Remove a specific listener from a specific event.
535 * @param {string} event Type of event to remove listener from
536 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
537 * to "on". Omit to remove all listeners.
538 * @param {Object} [context=null] Context object function or method call
540 * @throws {Error} Listener argument is not a function or a valid method name
542 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
545 if ( arguments
.length
=== 1 ) {
546 // Remove all bindings for event
547 delete this.bindings
[event
];
551 this.constructor.static.validateMethod( method
, context
);
553 if ( !( event
in this.bindings
) || !this.bindings
[event
].length
) {
554 // No matching bindings
558 // Default to null context
559 if ( arguments
.length
< 3 ) {
563 // Remove matching handlers
564 bindings
= this.bindings
[event
];
567 if ( bindings
[i
].method
=== method
&& bindings
[i
].context
=== context
) {
568 bindings
.splice( i
, 1 );
572 // Cleanup if now empty
573 if ( bindings
.length
=== 0 ) {
574 delete this.bindings
[event
];
582 * TODO: Should this be chainable? What is the usefulness of the boolean
585 * @param {string} event Type of event
586 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
587 * @return {boolean} If event was handled by at least one listener
589 oo
.EventEmitter
.prototype.emit = function ( event
) {
590 var i
, len
, binding
, bindings
, args
, method
;
592 if ( event
in this.bindings
) {
593 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
594 bindings
= this.bindings
[event
].slice();
595 args
= Array
.prototype.slice
.call( arguments
, 1 );
596 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
597 binding
= bindings
[i
];
598 if ( typeof binding
.method
=== 'string' ) {
599 // Lookup method by name (late binding)
600 method
= binding
.context
[ binding
.method
];
602 method
= binding
.method
;
606 binding
.args
? binding
.args
.concat( args
) : args
615 * Connect event handlers to an object.
617 * @param {Object} context Object to call methods on when events occur
618 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
619 * event bindings keyed by event name containing either method names, functions or arrays containing
620 * method name or function followed by a list of arguments to be passed to callback before emitted
624 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
625 var method
, args
, event
;
627 for ( event
in methods
) {
628 method
= methods
[event
];
629 // Allow providing additional args
630 if ( Array
.isArray( method
) ) {
631 args
= method
.slice( 1 );
637 this.on( event
, method
, args
, context
);
643 * Disconnect event handlers from an object.
645 * @param {Object} context Object to disconnect methods from
646 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
647 * event bindings keyed by event name. Values can be either method names or functions, but must be
648 * consistent with those used in the corresponding call to "connect".
651 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
652 var i
, event
, bindings
;
655 // Remove specific connections to the context
656 for ( event
in methods
) {
657 this.off( event
, methods
[event
], context
);
660 // Remove all connections to the context
661 for ( event
in this.bindings
) {
662 bindings
= this.bindings
[event
];
665 // bindings[i] may have been removed by the previous step's
666 // this.off so check it still exists
667 if ( bindings
[i
] && bindings
[i
].context
=== context
) {
668 this.off( event
, bindings
[i
].method
, context
);
678 * Validate a function or method call in a context
680 * For a method name, check that it names a function in the context object
683 * @param {Function|string} method Function or method name
684 * @param {Mixed} context The context of the call
685 * @throws {Error} A method name is given but there is no context
686 * @throws {Error} In the context object, no property exists with the given name
687 * @throws {Error} In the context object, the named property is not a function
689 oo
.EventEmitter
.static.validateMethod = function ( method
, context
) {
690 // Validate method and context
691 if ( typeof method
=== 'string' ) {
693 if ( context
=== undefined || context
=== null ) {
694 throw new Error( 'Method name "' + method
+ '" has no context.' );
696 if ( !( method
in context
) ) {
697 // Technically the method does not need to exist yet: it could be
698 // added before call time. But this probably signals a typo.
699 throw new Error( 'Method not found: "' + method
+ '"' );
701 if ( typeof context
[method
] !== 'function' ) {
702 // Technically the property could be replaced by a function before
703 // call time. But this probably signals a typo.
704 throw new Error( 'Property "' + method
+ '" is not a function' );
706 } else if ( typeof method
!== 'function' ) {
707 throw new Error( 'Invalid callback. Function or method name expected.' );
715 * @mixins OO.EventEmitter
719 oo
.Registry
= function OoRegistry() {
720 // Mixin constructors
721 oo
.EventEmitter
.call( this );
729 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
735 * @param {string} name
736 * @param {Mixed} data
742 * Associate one or more symbolic names with some data.
744 * Only the base name will be registered, overriding any existing entry with the same base name.
746 * @param {string|string[]} name Symbolic name or list of symbolic names
747 * @param {Mixed} data Data to associate with symbolic name
749 * @throws {Error} Name argument must be a string or array
751 oo
.Registry
.prototype.register = function ( name
, data
) {
753 if ( typeof name
=== 'string' ) {
754 this.registry
[name
] = data
;
755 this.emit( 'register', name
, data
);
756 } else if ( Array
.isArray( name
) ) {
757 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
758 this.register( name
[i
], data
);
761 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
766 * Get data for a given symbolic name.
768 * Lookups are done using the base name.
770 * @param {string} name Symbolic name
771 * @return {Mixed|undefined} Data associated with symbolic name
773 oo
.Registry
.prototype.lookup = function ( name
) {
774 if ( hasOwn
.call( this.registry
, name
) ) {
775 return this.registry
[name
];
781 * @extends OO.Registry
785 oo
.Factory
= function OoFactory() {
786 oo
.Factory
.parent
.call( this );
794 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
799 * Register a constructor with the factory.
801 * Classes must have a static `name` property to be registered.
803 * function MyClass() {};
804 * OO.initClass( MyClass );
805 * // Adds a static property to the class defining a symbolic name
806 * MyClass.static.name = 'mine';
807 * // Registers class with factory, available via symbolic name 'mine'
808 * factory.register( MyClass );
810 * @param {Function} constructor Constructor to use when creating object
811 * @throws {Error} Name must be a string and must not be empty
812 * @throws {Error} Constructor must be a function
814 oo
.Factory
.prototype.register = function ( constructor ) {
817 if ( typeof constructor !== 'function' ) {
818 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
820 name
= constructor.static && constructor.static.name
;
821 if ( typeof name
!== 'string' || name
=== '' ) {
822 throw new Error( 'Name must be a string and must not be empty' );
824 this.entries
.push( name
);
826 oo
.Factory
.parent
.prototype.register
.call( this, name
, constructor );
830 * Create an object based on a name.
832 * Name is used to look up the constructor to use, while all additional arguments are passed to the
833 * constructor directly, so leaving one out will pass an undefined to the constructor.
835 * @param {string} name Object name
836 * @param {Mixed...} [args] Arguments to pass to the constructor
837 * @return {Object} The new object
838 * @throws {Error} Unknown object name
840 oo
.Factory
.prototype.create = function ( name
) {
842 constructor = this.lookup( name
);
844 if ( !constructor ) {
845 throw new Error( 'No class registered by that name: ' + name
);
848 // Convert arguments to array and shift the first argument (name) off
849 args
= Array
.prototype.slice
.call( arguments
, 1 );
851 // We can't use the "new" operator with .apply directly because apply needs a
852 // context. So instead just do what "new" does: create an object that inherits from
853 // the constructor's prototype (which also makes it an "instanceof" the constructor),
854 // then invoke the constructor with the object as context, and return it (ignoring
855 // the constructor's return value).
856 obj
= Object
.create( constructor.prototype );
857 constructor.apply( obj
, args
);
861 /*jshint node:true */
862 if ( typeof module
!== 'undefined' && module
.exports
) {