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: Wed Apr 02 2014 14:29:36 GMT-0700 (PDT)
11 ( function ( global
) {
16 * Namespace for all classes, static methods and static properties.
21 hasOwn
= oo
.hasOwnProperty
,
22 toString
= oo
.toString
;
27 * Assert whether a value is a plain object or not.
32 oo
.isPlainObject = function ( obj
) {
33 // Any object or value whose internal [[Class]] property is not "[object Object]"
34 if ( toString
.call( obj
) !== '[object Object]' ) {
38 // The try/catch suppresses exceptions thrown when attempting to access
39 // the "constructor" property of certain host objects suich as window.location
40 // in Firefox < 20 (https://bugzilla.mozilla.org/814622)
42 if ( obj
.constructor &&
43 !hasOwn
.call( obj
.constructor.prototype, 'isPrototypeOf' ) ) {
54 * Utility to initialize a class for OO inheritance.
56 * Currently this just initializes an empty static object.
58 * @param {Function} fn
60 oo
.initClass = function ( fn
) {
61 fn
.static = fn
.static || {};
65 * Utility for common usage of Object#create for inheriting from one
66 * prototype to another.
68 * Beware: This redefines the prototype, call before setting your prototypes.
69 * Beware: This redefines the prototype, can only be called once on a function.
70 * If called multiple times on the same function, the previous prototype is lost.
71 * This is how prototypal inheritance works, it can only be one straight chain
72 * (just like classical inheritance in PHP for example). If you need to work with
73 * multiple constructors consider storing an instance of the other constructor in a
74 * property instead, or perhaps use a mixin (see OO.mixinClass).
77 * Thing.prototype.exists = function () {};
80 * Person.super.apply( this, arguments );
82 * OO.inheritClass( Person, Thing );
83 * Person.static.defaultEyeCount = 2;
84 * Person.prototype.walk = function () {};
87 * Jumper.super.apply( this, arguments );
89 * OO.inheritClass( Jumper, Person );
90 * Jumper.prototype.jump = function () {};
92 * Jumper.static.defaultEyeCount === 2;
93 * var x = new Jumper();
96 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
98 * @param {Function} targetFn
99 * @param {Function} originFn
100 * @throws {Error} If target already inherits from origin
102 oo
.inheritClass = function ( targetFn
, originFn
) {
103 if ( targetFn
.prototype instanceof originFn
) {
104 throw new Error( 'Target already inherits from origin' );
107 var targetConstructor
= targetFn
.prototype.constructor;
109 targetFn
.super = originFn
;
110 targetFn
.prototype = Object
.create( originFn
.prototype, {
111 // Restore constructor property of targetFn
113 value
: targetConstructor
,
120 // Extend static properties - always initialize both sides
121 oo
.initClass( originFn
);
122 targetFn
.static = Object
.create( originFn
.static );
126 * Utility to copy over *own* prototype properties of a mixin.
127 * The 'constructor' (whether implicit or explicit) is not copied over.
129 * This does not create inheritance to the origin. If inheritance is needed
130 * use oo.inheritClass instead.
132 * Beware: This can redefine a prototype property, call before setting your prototypes.
133 * Beware: Don't call before oo.inheritClass.
136 * function Context() {}
138 * // Avoid repeating this code
139 * function ContextLazyLoad() {}
140 * ContextLazyLoad.prototype.getContext = function () {
141 * if ( !this.context ) {
142 * this.context = new Context();
144 * return this.context;
147 * function FooBar() {}
148 * OO.inheritClass( FooBar, Foo );
149 * OO.mixinClass( FooBar, ContextLazyLoad );
151 * @param {Function} targetFn
152 * @param {Function} originFn
154 oo
.mixinClass = function ( targetFn
, originFn
) {
157 // Copy prototype properties
158 for ( key
in originFn
.prototype ) {
159 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
160 targetFn
.prototype[key
] = originFn
.prototype[key
];
164 // Copy static properties - always initialize both sides
165 oo
.initClass( targetFn
);
166 if ( originFn
.static ) {
167 for ( key
in originFn
.static ) {
168 if ( hasOwn
.call( originFn
.static, key
) ) {
169 targetFn
.static[key
] = originFn
.static[key
];
173 oo
.initClass( originFn
);
180 * Create a new object that is an instance of the same
181 * constructor as the input, inherits from the same object
182 * and contains the same own properties.
184 * This makes a shallow non-recursive copy of own properties.
185 * To create a recursive copy of plain objects, use #copy.
187 * var foo = new Person( mom, dad );
189 * var foo2 = OO.cloneObject( foo );
193 * foo2 !== foo; // true
194 * foo2 instanceof Person; // true
195 * foo2.getAge(); // 21
196 * foo.getAge(); // 22
198 * @param {Object} origin
199 * @return {Object} Clone of origin
201 oo
.cloneObject = function ( origin
) {
204 r
= Object
.create( origin
.constructor.prototype );
206 for ( key
in origin
) {
207 if ( hasOwn
.call( origin
, key
) ) {
208 r
[key
] = origin
[key
];
216 * Get an array of all property values in an object.
218 * @param {Object} Object to get values from
219 * @return {Array} List of object values
221 oo
.getObjectValues = function ( obj
) {
224 if ( obj
!== Object( obj
) ) {
225 throw new TypeError( 'Called on non-object' );
230 if ( hasOwn
.call( obj
, key
) ) {
231 values
[values
.length
] = obj
[key
];
239 * Recursively compares properties between two objects.
241 * A false result may be caused by property inequality or by properties in one object missing from
242 * the other. An asymmetrical test may also be performed, which checks only that properties in the
243 * first object are present in the second object, but not the inverse.
245 * @param {Object} a First object to compare
246 * @param {Object} b Second object to compare
247 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
248 * @return {boolean} If the objects contain the same values as each other
250 oo
.compare = function ( a
, b
, asymmetrical
) {
251 var aValue
, bValue
, aType
, bType
, k
;
260 aType
= typeof aValue
;
261 bType
= typeof bValue
;
262 if ( aType
!== bType
||
263 ( ( aType
=== 'string' || aType
=== 'number' ) && aValue
!== bValue
) ||
264 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
268 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
269 return asymmetrical
? true : oo
.compare( b
, a
, true );
273 * Create a plain deep copy of any kind of object.
275 * Copies are deep, and will either be an object or an array depending on `source`.
277 * @param {Object} source Object to copy
278 * @param {Function} [callback] Applied to leaf values before they added to the clone
279 * @return {Object} Copy of source object
281 oo
.copy = function ( source
, callback
) {
282 var key
, sourceValue
, sourceType
, destination
;
284 if ( typeof source
.clone
=== 'function' ) {
285 return source
.clone();
288 destination
= Array
.isArray( source
) ? new Array( source
.length
) : {};
290 for ( key
in source
) {
291 sourceValue
= source
[key
];
292 sourceType
= typeof sourceValue
;
293 if ( Array
.isArray( sourceValue
) ) {
295 destination
[key
] = oo
.copy( sourceValue
, callback
);
296 } else if ( sourceValue
&& typeof sourceValue
.clone
=== 'function' ) {
297 // Duck type object with custom clone method
298 destination
[key
] = callback
?
299 callback( sourceValue
.clone() ) : sourceValue
.clone();
300 } else if ( sourceValue
&& typeof sourceValue
.cloneNode
=== 'function' ) {
302 destination
[key
] = callback
?
303 callback( sourceValue
.cloneNode( true ) ) : sourceValue
.cloneNode( true );
304 } else if ( oo
.isPlainObject( sourceValue
) ) {
306 destination
[key
] = oo
.copy( sourceValue
, callback
);
308 // Non-plain objects (incl. functions) and primitive values
309 destination
[key
] = callback
? callback( sourceValue
) : sourceValue
;
317 * Generate a hash of an object based on its name and data.
319 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
321 * To avoid two objects with the same values generating different hashes, we utilize the replacer
322 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
323 * not be the fastest way to do this; we should investigate this further.
325 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
326 * function, we call that function and use its return value rather than hashing the object
327 * ourselves. This allows classes to define custom hashing.
329 * @param {Object} val Object to generate hash for
330 * @return {string} Hash of object
332 oo
.getHash = function ( val
) {
333 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
337 * Helper function for OO.getHash which sorts objects by key.
339 * This is a callback passed into JSON.stringify.
341 * @method getHash_keySortReplacer
342 * @param {string} key Property name of value being replaced
343 * @param {Mixed} val Property value to replace
344 * @return {Mixed} Replacement value
346 oo
.getHash
.keySortReplacer = function ( key
, val
) {
347 var normalized
, keys
, i
, len
;
348 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
349 // This object has its own custom hash function, use it
350 val
= val
.getHashObject();
352 if ( !Array
.isArray( val
) && Object( val
) === val
) {
353 // Only normalize objects when the key-order is ambiguous
354 // (e.g. any object not an array).
356 keys
= Object
.keys( val
).sort();
359 for ( ; i
< len
; i
+= 1 ) {
360 normalized
[keys
[i
]] = val
[keys
[i
]];
364 // Primitive values and arrays get stable hashes
365 // by default. Lets those be stringified as-is.
372 * Compute the union (duplicate-free merge) of a set of arrays.
374 * Arrays values must be convertable to object keys (strings).
376 * By building an object (with the values for keys) in parallel with
377 * the array, a new item's existence in the union can be computed faster.
379 * @param {Array...} arrays Arrays to union
380 * @return {Array} Union of the arrays
382 oo
.simpleArrayUnion = function () {
383 var i
, ilen
, arr
, j
, jlen
,
387 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
389 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
390 if ( !obj
[ arr
[j
] ] ) {
391 obj
[ arr
[j
] ] = true;
392 result
.push( arr
[j
] );
401 * Combine arrays (intersection or difference).
403 * An intersection checks the item exists in 'b' while difference checks it doesn't.
405 * Arrays values must be convertable to object keys (strings).
407 * By building an object (with the values for keys) of 'b' we can
408 * compute the result faster.
411 * @param {Array} a First array
412 * @param {Array} b Second array
413 * @param {boolean} includeB Whether to items in 'b'
414 * @return {Array} Combination (intersection or difference) of arrays
416 function simpleArrayCombine( a
, b
, includeB
) {
421 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
425 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
426 isInB
= !!bObj
[ a
[i
] ];
427 if ( isInB
=== includeB
) {
436 * Compute the intersection of two arrays (items in both arrays).
438 * Arrays values must be convertable to object keys (strings).
440 * @param {Array} a First array
441 * @param {Array} b Second array
442 * @return {Array} Intersection of arrays
444 oo
.simpleArrayIntersection = function ( a
, b
) {
445 return simpleArrayCombine( a
, b
, true );
449 * Compute the difference of two arrays (items in 'a' but not 'b').
451 * Arrays values must be convertable to object keys (strings).
453 * @param {Array} a First array
454 * @param {Array} b Second array
455 * @return {Array} Intersection of arrays
457 oo
.simpleArrayDifference = function ( a
, b
) {
458 return simpleArrayCombine( a
, b
, false );
461 * @class OO.EventEmitter
465 oo
.EventEmitter
= function OoEventEmitter() {
469 * Storage of bound event handlers by event name.
479 * Add a listener to events of a specific event.
481 * If the callback/context are already bound to the event, they will not be bound again.
483 * @param {string} event Type of event to listen to
484 * @param {Function} callback Function to call when event occurs
485 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
486 * @param {Object} [context=null] Object to use as context for callback function or call method on
487 * @throws {Error} Listener argument is not a function or method name
490 oo
.EventEmitter
.prototype.on = function ( event
, callback
, args
, context
) {
491 var i
, bindings
, binding
;
494 if ( typeof callback
!== 'function' ) {
495 throw new Error( 'Invalid callback. Function or method name expected.' );
497 // Fallback to null context
498 if ( arguments
.length
< 4 ) {
501 if ( this.bindings
.hasOwnProperty( event
) ) {
502 // Check for duplicate callback and context for this event
503 bindings
= this.bindings
[event
];
506 binding
= bindings
[i
];
507 if ( bindings
.callback
=== callback
&& bindings
.context
=== context
) {
512 // Auto-initialize bindings list
513 bindings
= this.bindings
[event
] = [];
525 * Adds a one-time listener to a specific event.
527 * @param {string} event Type of event to listen to
528 * @param {Function} listener Listener to call when event occurs
531 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
532 var eventEmitter
= this;
533 return this.on( event
, function listenerWrapper() {
534 eventEmitter
.off( event
, listenerWrapper
);
535 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
540 * Remove a specific listener from a specific event.
542 * @param {string} event Type of event to remove listener from
543 * @param {Function} [callback] Listener to remove, omit to remove all
544 * @param {Object} [context=null] Object used context for callback function or method
546 * @throws {Error} Listener argument is not a function
548 oo
.EventEmitter
.prototype.off = function ( event
, callback
, context
) {
551 if ( arguments
.length
=== 1 ) {
552 // Remove all bindings for event
553 if ( event
in this.bindings
) {
554 delete this.bindings
[event
];
557 if ( typeof callback
!== 'function' ) {
558 throw new Error( 'Invalid callback. Function expected.' );
560 if ( !( event
in this.bindings
) || !this.bindings
[event
].length
) {
561 // No matching bindings
564 // Fallback to null context
565 if ( arguments
.length
< 3 ) {
568 // Remove matching handlers
569 bindings
= this.bindings
[event
];
572 if ( bindings
[i
].callback
=== callback
&& bindings
[i
].context
=== context
) {
573 bindings
.splice( i
, 1 );
576 // Cleanup if now empty
577 if ( bindings
.length
=== 0 ) {
578 delete this.bindings
[event
];
587 * TODO: Should this be chainable? What is the usefulness of the boolean
590 * @param {string} event Type of event
591 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
592 * @return {boolean} If event was handled by at least one listener
594 oo
.EventEmitter
.prototype.emit = function ( event
) {
595 var i
, len
, binding
, bindings
, args
;
597 if ( event
in this.bindings
) {
598 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
599 bindings
= this.bindings
[event
].slice();
600 args
= Array
.prototype.slice
.call( arguments
, 1 );
601 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
602 binding
= bindings
[i
];
603 binding
.callback
.apply(
605 binding
.args
? binding
.args
.concat( args
) : args
614 * Connect event handlers to an object.
616 * @param {Object} context Object to call methods on when events occur
617 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
618 * event bindings keyed by event name containing either method names, functions or arrays containing
619 * method name or function followed by a list of arguments to be passed to callback before emitted
623 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
624 var method
, callback
, args
, event
;
626 for ( event
in methods
) {
627 method
= methods
[event
];
628 // Allow providing additional args
629 if ( Array
.isArray( method
) ) {
630 args
= method
.slice( 1 );
635 // Allow callback to be a method name
636 if ( typeof method
=== 'string' ) {
638 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
639 throw new Error( 'Method not found: ' + method
);
641 // Resolve to function
642 callback
= context
[method
];
647 this.on
.apply( this, [ event
, callback
, args
, context
] );
653 * Disconnect event handlers from an object.
655 * @param {Object} context Object to disconnect methods from
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 or functions
660 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
661 var i
, method
, callback
, event
, bindings
;
664 // Remove specific connections to the context
665 for ( event
in methods
) {
666 method
= methods
[event
];
667 if ( typeof method
=== 'string' ) {
669 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
670 throw new Error( 'Method not found: ' + method
);
672 // Resolve to function
673 callback
= context
[method
];
677 this.off( event
, callback
, context
);
680 // Remove all connections to the context
681 for ( event
in this.bindings
) {
682 bindings
= this.bindings
[event
];
685 if ( bindings
[i
].context
=== context
) {
686 this.off( event
, bindings
[i
].callback
, context
);
696 * @mixins OO.EventEmitter
700 oo
.Registry
= function OoRegistry() {
701 // Mixin constructors
702 oo
.EventEmitter
.call( this );
710 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
716 * @param {string} name
717 * @param {Mixed} data
723 * Associate one or more symbolic names with some data.
725 * Only the base name will be registered, overriding any existing entry with the same base name.
727 * @param {string|string[]} name Symbolic name or list of symbolic names
728 * @param {Mixed} data Data to associate with symbolic name
730 * @throws {Error} Name argument must be a string or array
732 oo
.Registry
.prototype.register = function ( name
, data
) {
734 if ( typeof name
=== 'string' ) {
735 this.registry
[name
] = data
;
736 this.emit( 'register', name
, data
);
737 } else if ( Array
.isArray( name
) ) {
738 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
739 this.register( name
[i
], data
);
742 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
747 * Get data for a given symbolic name.
749 * Lookups are done using the base name.
751 * @param {string} name Symbolic name
752 * @return {Mixed|undefined} Data associated with symbolic name
754 oo
.Registry
.prototype.lookup = function ( name
) {
755 return this.registry
[name
];
759 * @extends OO.Registry
763 oo
.Factory
= function OoFactory() {
764 oo
.Factory
.super.call( this );
772 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
777 * Register a constructor with the factory.
779 * Classes must have a static `name` property to be registered.
781 * function MyClass() {};
782 * OO.initClass( MyClass );
783 * // Adds a static property to the class defining a symbolic name
784 * MyClass.static.name = 'mine';
785 * // Registers class with factory, available via symbolic name 'mine'
786 * factory.register( MyClass );
788 * @param {Function} constructor Constructor to use when creating object
789 * @throws {Error} Name must be a string and must not be empty
790 * @throws {Error} Constructor must be a function
792 oo
.Factory
.prototype.register = function ( constructor ) {
795 if ( typeof constructor !== 'function' ) {
796 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
798 name
= constructor.static && constructor.static.name
;
799 if ( typeof name
!== 'string' || name
=== '' ) {
800 throw new Error( 'Name must be a string and must not be empty' );
802 this.entries
.push( name
);
804 oo
.Factory
.super.prototype.register
.call( this, name
, constructor );
808 * Create an object based on a name.
810 * Name is used to look up the constructor to use, while all additional arguments are passed to the
811 * constructor directly, so leaving one out will pass an undefined to the constructor.
813 * @param {string} name Object name
814 * @param {Mixed...} [args] Arguments to pass to the constructor
815 * @return {Object} The new object
816 * @throws {Error} Unknown object name
818 oo
.Factory
.prototype.create = function ( name
) {
819 var args
, obj
, constructor;
821 if ( !this.registry
.hasOwnProperty( name
) ) {
822 throw new Error( 'No class registered by that name: ' + name
);
824 constructor = this.registry
[name
];
826 // Convert arguments to array and shift the first argument (name) off
827 args
= Array
.prototype.slice
.call( arguments
, 1 );
829 // We can't use the "new" operator with .apply directly because apply needs a
830 // context. So instead just do what "new" does: create an object that inherits from
831 // the constructor's prototype (which also makes it an "instanceof" the constructor),
832 // then invoke the constructor with the object as context, and return it (ignoring
833 // the constructor's return value).
834 obj
= Object
.create( constructor.prototype );
835 constructor.apply( obj
, args
);
838 /*jshint node:true */
839 if ( typeof module
!== 'undefined' && module
.exports
) {