2 * OOjs v1.1.2 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-11-06T17:42:36Z
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 * Inherit from prototype to another using Object#create.
42 * 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 * Copy over *own* prototype properties of a mixin.
108 * The 'constructor' (whether implicit or explicit) is not copied over.
110 * This does not create inheritance to the origin. If inheritance is needed
111 * use oo.inheritClass instead.
113 * Beware: This can redefine a prototype property, call before setting your prototypes.
115 * Beware: Don't call before oo.inheritClass.
118 * function Context() {}
120 * // Avoid repeating this code
121 * function ContextLazyLoad() {}
122 * ContextLazyLoad.prototype.getContext = function () {
123 * if ( !this.context ) {
124 * this.context = new Context();
126 * return this.context;
129 * function FooBar() {}
130 * OO.inheritClass( FooBar, Foo );
131 * OO.mixinClass( FooBar, ContextLazyLoad );
133 * @param {Function} targetFn
134 * @param {Function} originFn
136 oo
.mixinClass = function ( targetFn
, originFn
) {
139 // Copy prototype properties
140 for ( key
in originFn
.prototype ) {
141 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
142 targetFn
.prototype[key
] = originFn
.prototype[key
];
146 // Copy static properties - always initialize both sides
147 oo
.initClass( targetFn
);
148 if ( originFn
.static ) {
149 for ( key
in originFn
.static ) {
150 if ( hasOwn
.call( originFn
.static, key
) ) {
151 targetFn
.static[key
] = originFn
.static[key
];
155 oo
.initClass( originFn
);
162 * Create a new object that is an instance of the same
163 * constructor as the input, inherits from the same object
164 * and contains the same own properties.
166 * This makes a shallow non-recursive copy of own properties.
167 * To create a recursive copy of plain objects, use #copy.
169 * var foo = new Person( mom, dad );
171 * var foo2 = OO.cloneObject( foo );
175 * foo2 !== foo; // true
176 * foo2 instanceof Person; // true
177 * foo2.getAge(); // 21
178 * foo.getAge(); // 22
180 * @param {Object} origin
181 * @return {Object} Clone of origin
183 oo
.cloneObject = function ( origin
) {
186 r
= Object
.create( origin
.constructor.prototype );
188 for ( key
in origin
) {
189 if ( hasOwn
.call( origin
, key
) ) {
190 r
[key
] = origin
[key
];
198 * Get an array of all property values in an object.
200 * @param {Object} Object to get values from
201 * @return {Array} List of object values
203 oo
.getObjectValues = function ( obj
) {
206 if ( obj
!== Object( obj
) ) {
207 throw new TypeError( 'Called on non-object' );
212 if ( hasOwn
.call( obj
, key
) ) {
213 values
[values
.length
] = obj
[key
];
221 * Recursively compare properties between two objects.
223 * A false result may be caused by property inequality or by properties in one object missing from
224 * the other. An asymmetrical test may also be performed, which checks only that properties in the
225 * first object are present in the second object, but not the inverse.
227 * If either a or b is null or undefined it will be treated as an empty object.
229 * @param {Object|undefined|null} a First object to compare
230 * @param {Object|undefined|null} b Second object to compare
231 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
232 * @return {boolean} If the objects contain the same values as each other
234 oo
.compare = function ( a
, b
, asymmetrical
) {
235 var aValue
, bValue
, aType
, bType
, k
;
245 if ( !hasOwn
.call( a
, k
) ) {
246 // Support es3-shim: Without this filter, comparing [] to {} will be false in ES3
247 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
253 aType
= typeof aValue
;
254 bType
= typeof bValue
;
255 if ( aType
!== bType
||
257 ( aType
=== 'string' || aType
=== 'number' || aType
=== 'boolean' ) &&
260 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
264 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
265 return asymmetrical
? true : oo
.compare( b
, a
, true );
269 * Create a plain deep copy of any kind of object.
271 * Copies are deep, and will either be an object or an array depending on `source`.
273 * @param {Object} source Object to copy
274 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
275 * @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.
276 * @return {Object} Copy of source object
278 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
279 var key
, destination
;
281 if ( nodeCallback
) {
282 // Extensibility: check before attempting to clone source.
283 destination
= nodeCallback( source
);
284 if ( destination
!== undefined ) {
289 if ( Array
.isArray( source
) ) {
290 // Array (fall through)
291 destination
= new Array( source
.length
);
292 } else if ( source
&& typeof source
.clone
=== 'function' ) {
293 // Duck type object with custom clone method
294 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
295 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
297 return leafCallback
?
298 leafCallback( source
.cloneNode( true ) ) :
299 source
.cloneNode( true );
300 } else if ( oo
.isPlainObject( source
) ) {
301 // Plain objects (fall through)
304 // Non-plain objects (incl. functions) and primitive values
305 return leafCallback
? leafCallback( source
) : source
;
308 // source is an array or a plain object
309 for ( key
in source
) {
310 destination
[key
] = oo
.copy( source
[key
], leafCallback
, nodeCallback
);
313 // This is an internal node, so we don't apply the leafCallback.
318 * Generate a hash of an object based on its name and data.
320 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
322 * To avoid two objects with the same values generating different hashes, we utilize the replacer
323 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
324 * not be the fastest way to do this; we should investigate this further.
326 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
327 * function, we call that function and use its return value rather than hashing the object
328 * ourselves. This allows classes to define custom hashing.
330 * @param {Object} val Object to generate hash for
331 * @return {string} Hash of object
333 oo
.getHash = function ( val
) {
334 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
338 * Sort objects by key (helper function for OO.getHash).
340 * This is a callback passed into JSON.stringify.
342 * @method getHash_keySortReplacer
343 * @param {string} key Property name of value being replaced
344 * @param {Mixed} val Property value to replace
345 * @return {Mixed} Replacement value
347 oo
.getHash
.keySortReplacer = function ( key
, val
) {
348 var normalized
, keys
, i
, len
;
349 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
350 // This object has its own custom hash function, use it
351 val
= val
.getHashObject();
353 if ( !Array
.isArray( val
) && Object( val
) === val
) {
354 // Only normalize objects when the key-order is ambiguous
355 // (e.g. any object not an array).
357 keys
= Object
.keys( val
).sort();
360 for ( ; i
< len
; i
+= 1 ) {
361 normalized
[keys
[i
]] = val
[keys
[i
]];
365 // Primitive values and arrays get stable hashes
366 // by default. Lets those be stringified as-is.
373 * Compute the union (duplicate-free merge) of a set of arrays.
375 * Arrays values must be convertable to object keys (strings).
377 * By building an object (with the values for keys) in parallel with
378 * the array, a new item's existence in the union can be computed faster.
380 * @param {Array...} arrays Arrays to union
381 * @return {Array} Union of the arrays
383 oo
.simpleArrayUnion = function () {
384 var i
, ilen
, arr
, j
, jlen
,
388 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
390 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
391 if ( !obj
[ arr
[j
] ] ) {
392 obj
[ arr
[j
] ] = true;
393 result
.push( arr
[j
] );
402 * Combine arrays (intersection or difference).
404 * An intersection checks the item exists in 'b' while difference checks it doesn't.
406 * Arrays values must be convertable to object keys (strings).
408 * By building an object (with the values for keys) of 'b' we can
409 * compute the result faster.
412 * @param {Array} a First array
413 * @param {Array} b Second array
414 * @param {boolean} includeB Whether to items in 'b'
415 * @return {Array} Combination (intersection or difference) of arrays
417 function simpleArrayCombine( a
, b
, includeB
) {
422 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
426 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
427 isInB
= !!bObj
[ a
[i
] ];
428 if ( isInB
=== includeB
) {
437 * Compute the intersection of two arrays (items in both arrays).
439 * Arrays values must be convertable to object keys (strings).
441 * @param {Array} a First array
442 * @param {Array} b Second array
443 * @return {Array} Intersection of arrays
445 oo
.simpleArrayIntersection = function ( a
, b
) {
446 return simpleArrayCombine( a
, b
, true );
450 * Compute the difference of two arrays (items in 'a' but not 'b').
452 * Arrays values must be convertable to object keys (strings).
454 * @param {Array} a First array
455 * @param {Array} b Second array
456 * @return {Array} Intersection of arrays
458 oo
.simpleArrayDifference = function ( a
, b
) {
459 return simpleArrayCombine( a
, b
, false );
464 oo
.isPlainObject
= $.isPlainObject
;
471 * @class OO.EventEmitter
475 oo
.EventEmitter
= function OoEventEmitter() {
479 * Storage of bound event handlers by event name.
486 oo
.initClass( oo
.EventEmitter
);
488 /* Private helper functions */
491 * Validate a function or method call in a context
493 * For a method name, check that it names a function in the context object
496 * @param {Function|string} method Function or method name
497 * @param {Mixed} context The context of the call
498 * @throws {Error} A method name is given but there is no context
499 * @throws {Error} In the context object, no property exists with the given name
500 * @throws {Error} In the context object, the named property is not a function
502 function validateMethod( method
, context
) {
503 // Validate method and context
504 if ( typeof method
=== 'string' ) {
506 if ( context
=== undefined || context
=== null ) {
507 throw new Error( 'Method name "' + method
+ '" has no context.' );
509 if ( typeof context
[method
] !== 'function' ) {
510 // Technically the property could be replaced by a function before
511 // call time. But this probably signals a typo.
512 throw new Error( 'Property "' + method
+ '" is not a function' );
514 } else if ( typeof method
!== 'function' ) {
515 throw new Error( 'Invalid callback. Function or method name expected.' );
522 * Add a listener to events of a specific event.
524 * The listener can be a function or the string name of a method; if the latter, then the
525 * name lookup happens at the time the listener is called.
527 * @param {string} event Type of event to listen to
528 * @param {Function|string} method Function or method name to call when event occurs
529 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
530 * @param {Object} [context=null] Context object for function or method call
531 * @throws {Error} Listener argument is not a function or a valid method name
534 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
537 validateMethod( method
, context
);
539 if ( hasOwn
.call( this.bindings
, event
) ) {
540 bindings
= this.bindings
[event
];
542 // Auto-initialize bindings list
543 bindings
= this.bindings
[event
] = [];
549 context
: ( arguments
.length
< 4 ) ? null : context
555 * Add a one-time listener to a specific event.
557 * @param {string} event Type of event to listen to
558 * @param {Function} listener Listener to call when event occurs
561 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
562 var eventEmitter
= this,
563 listenerWrapper = function () {
564 eventEmitter
.off( event
, listenerWrapper
);
565 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
567 return this.on( event
, listenerWrapper
);
571 * Remove a specific listener from a specific event.
573 * @param {string} event Type of event to remove listener from
574 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
575 * to "on". Omit to remove all listeners.
576 * @param {Object} [context=null] Context object function or method call
578 * @throws {Error} Listener argument is not a function or a valid method name
580 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
583 if ( arguments
.length
=== 1 ) {
584 // Remove all bindings for event
585 delete this.bindings
[event
];
589 validateMethod( method
, context
);
591 if ( !hasOwn
.call( this.bindings
, event
) || !this.bindings
[event
].length
) {
592 // No matching bindings
596 // Default to null context
597 if ( arguments
.length
< 3 ) {
601 // Remove matching handlers
602 bindings
= this.bindings
[event
];
605 if ( bindings
[i
].method
=== method
&& bindings
[i
].context
=== context
) {
606 bindings
.splice( i
, 1 );
610 // Cleanup if now empty
611 if ( bindings
.length
=== 0 ) {
612 delete this.bindings
[event
];
620 * TODO: Should this be chainable? What is the usefulness of the boolean
623 * @param {string} event Type of event
624 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
625 * @return {boolean} If event was handled by at least one listener
627 oo
.EventEmitter
.prototype.emit = function ( event
) {
628 var i
, len
, binding
, bindings
, args
, method
;
630 if ( hasOwn
.call( this.bindings
, event
) ) {
631 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
632 bindings
= this.bindings
[event
].slice();
633 args
= Array
.prototype.slice
.call( arguments
, 1 );
634 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
635 binding
= bindings
[i
];
636 if ( typeof binding
.method
=== 'string' ) {
637 // Lookup method by name (late binding)
638 method
= binding
.context
[ binding
.method
];
640 method
= binding
.method
;
644 binding
.args
? binding
.args
.concat( args
) : args
653 * Connect event handlers to an object.
655 * @param {Object} context Object to call methods on when events occur
656 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
657 * event bindings keyed by event name containing either method names, functions or arrays containing
658 * method name or function followed by a list of arguments to be passed to callback before emitted
662 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
663 var method
, args
, event
;
665 for ( event
in methods
) {
666 method
= methods
[event
];
667 // Allow providing additional args
668 if ( Array
.isArray( method
) ) {
669 args
= method
.slice( 1 );
675 this.on( event
, method
, args
, context
);
681 * Disconnect event handlers from an object.
683 * @param {Object} context Object to disconnect methods from
684 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
685 * event bindings keyed by event name. Values can be either method names or functions, but must be
686 * consistent with those used in the corresponding call to "connect".
689 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
690 var i
, event
, bindings
;
693 // Remove specific connections to the context
694 for ( event
in methods
) {
695 this.off( event
, methods
[event
], context
);
698 // Remove all connections to the context
699 for ( event
in this.bindings
) {
700 bindings
= this.bindings
[event
];
703 // bindings[i] may have been removed by the previous step's
704 // this.off so check it still exists
705 if ( bindings
[i
] && bindings
[i
].context
=== context
) {
706 this.off( event
, bindings
[i
].method
, context
);
721 * @mixins OO.EventEmitter
725 oo
.Registry
= function OoRegistry() {
726 // Mixin constructors
727 oo
.EventEmitter
.call( this );
735 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
741 * @param {string} name
742 * @param {Mixed} data
748 * Associate one or more symbolic names with some data.
750 * Only the base name will be registered, overriding any existing entry with the same base name.
752 * @param {string|string[]} name Symbolic name or list of symbolic names
753 * @param {Mixed} data Data to associate with symbolic name
755 * @throws {Error} Name argument must be a string or array
757 oo
.Registry
.prototype.register = function ( name
, data
) {
759 if ( typeof name
=== 'string' ) {
760 this.registry
[name
] = data
;
761 this.emit( 'register', name
, data
);
762 } else if ( Array
.isArray( name
) ) {
763 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
764 this.register( name
[i
], data
);
767 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
772 * Get data for a given symbolic name.
774 * Lookups are done using the base name.
776 * @param {string} name Symbolic name
777 * @return {Mixed|undefined} Data associated with symbolic name
779 oo
.Registry
.prototype.lookup = function ( name
) {
780 if ( hasOwn
.call( this.registry
, name
) ) {
781 return this.registry
[name
];
787 * @extends OO.Registry
791 oo
.Factory
= function OoFactory() {
792 oo
.Factory
.parent
.call( this );
800 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
805 * Register a constructor with the factory.
807 * Classes must have a static `name` property to be registered.
809 * function MyClass() {};
810 * OO.initClass( MyClass );
811 * // Adds a static property to the class defining a symbolic name
812 * MyClass.static.name = 'mine';
813 * // Registers class with factory, available via symbolic name 'mine'
814 * factory.register( MyClass );
816 * @param {Function} constructor Constructor to use when creating object
817 * @throws {Error} Name must be a string and must not be empty
818 * @throws {Error} Constructor must be a function
820 oo
.Factory
.prototype.register = function ( constructor ) {
823 if ( typeof constructor !== 'function' ) {
824 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
826 name
= constructor.static && constructor.static.name
;
827 if ( typeof name
!== 'string' || name
=== '' ) {
828 throw new Error( 'Name must be a string and must not be empty' );
830 this.entries
.push( name
);
832 oo
.Factory
.parent
.prototype.register
.call( this, name
, constructor );
836 * Create an object based on a name.
838 * Name is used to look up the constructor to use, while all additional arguments are passed to the
839 * constructor directly, so leaving one out will pass an undefined to the constructor.
841 * @param {string} name Object name
842 * @param {Mixed...} [args] Arguments to pass to the constructor
843 * @return {Object} The new object
844 * @throws {Error} Unknown object name
846 oo
.Factory
.prototype.create = function ( name
) {
848 constructor = this.lookup( name
);
850 if ( !constructor ) {
851 throw new Error( 'No class registered by that name: ' + name
);
854 // Convert arguments to array and shift the first argument (name) off
855 args
= Array
.prototype.slice
.call( arguments
, 1 );
857 // We can't use the "new" operator with .apply directly because apply needs a
858 // context. So instead just do what "new" does: create an object that inherits from
859 // the constructor's prototype (which also makes it an "instanceof" the constructor),
860 // then invoke the constructor with the object as context, and return it (ignoring
861 // the constructor's return value).
862 obj
= Object
.create( constructor.prototype );
863 constructor.apply( obj
, args
);
867 /*jshint node:true */
868 if ( typeof module
!== 'undefined' && module
.exports
) {