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-07-23T20:15:47Z
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 * @param {Object} a First object to compare
226 * @param {Object} b Second object to compare
227 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
228 * @return {boolean} If the objects contain the same values as each other
230 oo
.compare = function ( a
, b
, asymmetrical
) {
231 var aValue
, bValue
, aType
, bType
, k
;
238 if ( !hasOwn
.call( a
, k
) ) {
239 // Support es3-shim: Without this filter, comparing [] to {} will be false in ES3
240 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
246 aType
= typeof aValue
;
247 bType
= typeof bValue
;
248 if ( aType
!== bType
||
249 ( ( aType
=== 'string' || aType
=== 'number' ) && aValue
!== bValue
) ||
250 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
254 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
255 return asymmetrical
? true : oo
.compare( b
, a
, true );
259 * Create a plain deep copy of any kind of object.
261 * Copies are deep, and will either be an object or an array depending on `source`.
263 * @param {Object} source Object to copy
264 * @param {Function} [callback] Applied to leaf values before they added to the clone
265 * @return {Object} Copy of source object
267 oo
.copy = function ( source
, callback
) {
268 var key
, sourceValue
, sourceType
, destination
;
270 if ( typeof source
.clone
=== 'function' ) {
271 return source
.clone();
274 destination
= Array
.isArray( source
) ? new Array( source
.length
) : {};
276 for ( key
in source
) {
277 sourceValue
= source
[key
];
278 sourceType
= typeof sourceValue
;
279 if ( Array
.isArray( sourceValue
) ) {
281 destination
[key
] = oo
.copy( sourceValue
, callback
);
282 } else if ( sourceValue
&& typeof sourceValue
.clone
=== 'function' ) {
283 // Duck type object with custom clone method
284 destination
[key
] = callback
?
285 callback( sourceValue
.clone() ) : sourceValue
.clone();
286 } else if ( sourceValue
&& typeof sourceValue
.cloneNode
=== 'function' ) {
288 destination
[key
] = callback
?
289 callback( sourceValue
.cloneNode( true ) ) : sourceValue
.cloneNode( true );
290 } else if ( oo
.isPlainObject( sourceValue
) ) {
292 destination
[key
] = oo
.copy( sourceValue
, callback
);
294 // Non-plain objects (incl. functions) and primitive values
295 destination
[key
] = callback
? callback( sourceValue
) : sourceValue
;
303 * Generate a hash of an object based on its name and data.
305 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
307 * To avoid two objects with the same values generating different hashes, we utilize the replacer
308 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
309 * not be the fastest way to do this; we should investigate this further.
311 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
312 * function, we call that function and use its return value rather than hashing the object
313 * ourselves. This allows classes to define custom hashing.
315 * @param {Object} val Object to generate hash for
316 * @return {string} Hash of object
318 oo
.getHash = function ( val
) {
319 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
323 * Helper function for OO.getHash which sorts objects by key.
325 * This is a callback passed into JSON.stringify.
327 * @method getHash_keySortReplacer
328 * @param {string} key Property name of value being replaced
329 * @param {Mixed} val Property value to replace
330 * @return {Mixed} Replacement value
332 oo
.getHash
.keySortReplacer = function ( key
, val
) {
333 var normalized
, keys
, i
, len
;
334 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
335 // This object has its own custom hash function, use it
336 val
= val
.getHashObject();
338 if ( !Array
.isArray( val
) && Object( val
) === val
) {
339 // Only normalize objects when the key-order is ambiguous
340 // (e.g. any object not an array).
342 keys
= Object
.keys( val
).sort();
345 for ( ; i
< len
; i
+= 1 ) {
346 normalized
[keys
[i
]] = val
[keys
[i
]];
350 // Primitive values and arrays get stable hashes
351 // by default. Lets those be stringified as-is.
358 * Compute the union (duplicate-free merge) of a set of arrays.
360 * Arrays values must be convertable to object keys (strings).
362 * By building an object (with the values for keys) in parallel with
363 * the array, a new item's existence in the union can be computed faster.
365 * @param {Array...} arrays Arrays to union
366 * @return {Array} Union of the arrays
368 oo
.simpleArrayUnion = function () {
369 var i
, ilen
, arr
, j
, jlen
,
373 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
375 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
376 if ( !obj
[ arr
[j
] ] ) {
377 obj
[ arr
[j
] ] = true;
378 result
.push( arr
[j
] );
387 * Combine arrays (intersection or difference).
389 * An intersection checks the item exists in 'b' while difference checks it doesn't.
391 * Arrays values must be convertable to object keys (strings).
393 * By building an object (with the values for keys) of 'b' we can
394 * compute the result faster.
397 * @param {Array} a First array
398 * @param {Array} b Second array
399 * @param {boolean} includeB Whether to items in 'b'
400 * @return {Array} Combination (intersection or difference) of arrays
402 function simpleArrayCombine( a
, b
, includeB
) {
407 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
411 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
412 isInB
= !!bObj
[ a
[i
] ];
413 if ( isInB
=== includeB
) {
422 * Compute the intersection of two arrays (items in both arrays).
424 * Arrays values must be convertable to object keys (strings).
426 * @param {Array} a First array
427 * @param {Array} b Second array
428 * @return {Array} Intersection of arrays
430 oo
.simpleArrayIntersection = function ( a
, b
) {
431 return simpleArrayCombine( a
, b
, true );
435 * Compute the difference of two arrays (items in 'a' but not 'b').
437 * Arrays values must be convertable to object keys (strings).
439 * @param {Array} a First array
440 * @param {Array} b Second array
441 * @return {Array} Intersection of arrays
443 oo
.simpleArrayDifference = function ( a
, b
) {
444 return simpleArrayCombine( a
, b
, false );
449 oo
.isPlainObject
= $.isPlainObject
;
454 * @class OO.EventEmitter
458 oo
.EventEmitter
= function OoEventEmitter() {
462 * Storage of bound event handlers by event name.
472 * Add a listener to events of a specific event.
474 * @param {string} event Type of event to listen to
475 * @param {Function} callback Function to call when event occurs
476 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
477 * @param {Object} [context=null] Object to use as context for callback function or call method on
478 * @throws {Error} Listener argument is not a function or method name
481 oo
.EventEmitter
.prototype.on = function ( event
, callback
, args
, context
) {
485 if ( typeof callback
!== 'function' ) {
486 throw new Error( 'Invalid callback. Function or method name expected.' );
488 // Fallback to null context
489 if ( arguments
.length
< 4 ) {
492 if ( hasOwn
.call( this.bindings
, event
) ) {
493 bindings
= this.bindings
[event
];
495 // Auto-initialize bindings list
496 bindings
= this.bindings
[event
] = [];
508 * Adds a one-time listener to a specific event.
510 * @param {string} event Type of event to listen to
511 * @param {Function} listener Listener to call when event occurs
514 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
515 var eventEmitter
= this,
516 listenerWrapper = function () {
517 eventEmitter
.off( event
, listenerWrapper
);
518 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
520 return this.on( event
, listenerWrapper
);
524 * Remove a specific listener from a specific event.
526 * @param {string} event Type of event to remove listener from
527 * @param {Function} [callback] Listener to remove, omit to remove all
528 * @param {Object} [context=null] Object used context for callback function or method
530 * @throws {Error} Listener argument is not a function
532 oo
.EventEmitter
.prototype.off = function ( event
, callback
, context
) {
535 if ( arguments
.length
=== 1 ) {
536 // Remove all bindings for event
537 delete this.bindings
[event
];
539 if ( typeof callback
!== 'function' ) {
540 throw new Error( 'Invalid callback. Function expected.' );
542 if ( !( event
in this.bindings
) || !this.bindings
[event
].length
) {
543 // No matching bindings
546 // Fallback to null context
547 if ( arguments
.length
< 3 ) {
550 // Remove matching handlers
551 bindings
= this.bindings
[event
];
554 if ( bindings
[i
].callback
=== callback
&& bindings
[i
].context
=== context
) {
555 bindings
.splice( i
, 1 );
558 // Cleanup if now empty
559 if ( bindings
.length
=== 0 ) {
560 delete this.bindings
[event
];
569 * TODO: Should this be chainable? What is the usefulness of the boolean
572 * @param {string} event Type of event
573 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
574 * @return {boolean} If event was handled by at least one listener
576 oo
.EventEmitter
.prototype.emit = function ( event
) {
577 var i
, len
, binding
, bindings
, args
;
579 if ( event
in this.bindings
) {
580 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
581 bindings
= this.bindings
[event
].slice();
582 args
= Array
.prototype.slice
.call( arguments
, 1 );
583 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
584 binding
= bindings
[i
];
585 binding
.callback
.apply(
587 binding
.args
? binding
.args
.concat( args
) : args
596 * Connect event handlers to an object.
598 * @param {Object} context Object to call methods on when events occur
599 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
600 * event bindings keyed by event name containing either method names, functions or arrays containing
601 * method name or function followed by a list of arguments to be passed to callback before emitted
605 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
606 var method
, callback
, args
, event
;
608 for ( event
in methods
) {
609 method
= methods
[event
];
610 // Allow providing additional args
611 if ( Array
.isArray( method
) ) {
612 args
= method
.slice( 1 );
617 // Allow callback to be a method name
618 if ( typeof method
=== 'string' ) {
620 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
621 throw new Error( 'Method not found: ' + method
);
623 // Resolve to function
624 callback
= context
[method
];
629 this.on
.apply( this, [ event
, callback
, args
, context
] );
635 * Disconnect event handlers from an object.
637 * @param {Object} context Object to disconnect methods from
638 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
639 * event bindings keyed by event name containing either method names or functions
642 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
643 var i
, method
, callback
, event
, bindings
;
646 // Remove specific connections to the context
647 for ( event
in methods
) {
648 method
= methods
[event
];
649 if ( typeof method
=== 'string' ) {
651 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
652 throw new Error( 'Method not found: ' + method
);
654 // Resolve to function
655 callback
= context
[method
];
659 this.off( event
, callback
, context
);
662 // Remove all connections to the context
663 for ( event
in this.bindings
) {
664 bindings
= this.bindings
[event
];
667 // bindings[i] may have been removed by the previous step's
668 // this.off so check it still exists
669 if ( bindings
[i
] && bindings
[i
].context
=== context
) {
670 this.off( event
, bindings
[i
].callback
, context
);
681 * @mixins OO.EventEmitter
685 oo
.Registry
= function OoRegistry() {
686 // Mixin constructors
687 oo
.EventEmitter
.call( this );
695 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
701 * @param {string} name
702 * @param {Mixed} data
708 * Associate one or more symbolic names with some data.
710 * Only the base name will be registered, overriding any existing entry with the same base name.
712 * @param {string|string[]} name Symbolic name or list of symbolic names
713 * @param {Mixed} data Data to associate with symbolic name
715 * @throws {Error} Name argument must be a string or array
717 oo
.Registry
.prototype.register = function ( name
, data
) {
719 if ( typeof name
=== 'string' ) {
720 this.registry
[name
] = data
;
721 this.emit( 'register', name
, data
);
722 } else if ( Array
.isArray( name
) ) {
723 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
724 this.register( name
[i
], data
);
727 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
732 * Get data for a given symbolic name.
734 * Lookups are done using the base name.
736 * @param {string} name Symbolic name
737 * @return {Mixed|undefined} Data associated with symbolic name
739 oo
.Registry
.prototype.lookup = function ( name
) {
740 return this.registry
[name
];
745 * @extends OO.Registry
749 oo
.Factory
= function OoFactory() {
750 oo
.Factory
.parent
.call( this );
758 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
763 * Register a constructor with the factory.
765 * Classes must have a static `name` property to be registered.
767 * function MyClass() {};
768 * OO.initClass( MyClass );
769 * // Adds a static property to the class defining a symbolic name
770 * MyClass.static.name = 'mine';
771 * // Registers class with factory, available via symbolic name 'mine'
772 * factory.register( MyClass );
774 * @param {Function} constructor Constructor to use when creating object
775 * @throws {Error} Name must be a string and must not be empty
776 * @throws {Error} Constructor must be a function
778 oo
.Factory
.prototype.register = function ( constructor ) {
781 if ( typeof constructor !== 'function' ) {
782 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
784 name
= constructor.static && constructor.static.name
;
785 if ( typeof name
!== 'string' || name
=== '' ) {
786 throw new Error( 'Name must be a string and must not be empty' );
788 this.entries
.push( name
);
790 oo
.Factory
.parent
.prototype.register
.call( this, name
, constructor );
794 * Create an object based on a name.
796 * Name is used to look up the constructor to use, while all additional arguments are passed to the
797 * constructor directly, so leaving one out will pass an undefined to the constructor.
799 * @param {string} name Object name
800 * @param {Mixed...} [args] Arguments to pass to the constructor
801 * @return {Object} The new object
802 * @throws {Error} Unknown object name
804 oo
.Factory
.prototype.create = function ( name
) {
805 var args
, obj
, constructor;
807 if ( !this.registry
.hasOwnProperty( name
) ) {
808 throw new Error( 'No class registered by that name: ' + name
);
810 constructor = this.registry
[name
];
812 // Convert arguments to array and shift the first argument (name) off
813 args
= Array
.prototype.slice
.call( arguments
, 1 );
815 // We can't use the "new" operator with .apply directly because apply needs a
816 // context. So instead just do what "new" does: create an object that inherits from
817 // the constructor's prototype (which also makes it an "instanceof" the constructor),
818 // then invoke the constructor with the object as context, and return it (ignoring
819 // the constructor's return value).
820 obj
= Object
.create( constructor.prototype );
821 constructor.apply( obj
, args
);
825 /*jshint node:true */
826 if ( typeof module
!== 'undefined' && module
.exports
) {