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: Tue Mar 11 2014 19:27:31 GMT+0100 (CET)
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 for common usage of Object#create for inheriting from one
55 * prototype to another.
57 * Beware: This redefines the prototype, call before setting your prototypes.
58 * Beware: This redefines the prototype, can only be called once on a function.
59 * If called multiple times on the same function, the previous prototype is lost.
60 * This is how prototypal inheritance works, it can only be one straight chain
61 * (just like classical inheritance in PHP for example). If you need to work with
62 * multiple constructors consider storing an instance of the other constructor in a
63 * property instead, or perhaps use a mixin (see OO.mixinClass).
66 * Thing.prototype.exists = function () {};
69 * Person.super.apply( this, arguments );
71 * OO.inheritClass( Person, Thing );
72 * Person.static.defaultEyeCount = 2;
73 * Person.prototype.walk = function () {};
76 * Jumper.super.apply( this, arguments );
78 * OO.inheritClass( Jumper, Person );
79 * Jumper.prototype.jump = function () {};
81 * Jumper.static.defaultEyeCount === 2;
82 * var x = new Jumper();
85 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
87 * @param {Function} targetFn
88 * @param {Function} originFn
89 * @throws {Error} If target already inherits from origin
91 oo
.inheritClass = function ( targetFn
, originFn
) {
92 if ( targetFn
.prototype instanceof originFn
) {
93 throw new Error( 'Target already inherits from origin' );
96 var targetConstructor
= targetFn
.prototype.constructor;
98 targetFn
.super = originFn
;
99 targetFn
.prototype = Object
.create( originFn
.prototype, {
100 // Restore constructor property of targetFn
102 value
: targetConstructor
,
109 // Extend static properties - always initialize both sides
110 originFn
.static = originFn
.static || {};
111 targetFn
.static = Object
.create( originFn
.static );
115 * Utility to copy over *own* prototype properties of a mixin.
116 * The 'constructor' (whether implicit or explicit) is not copied over.
118 * This does not create inheritance to the origin. If inheritance is needed
119 * use oo.inheritClass instead.
121 * Beware: This can redefine a prototype property, call before setting your prototypes.
122 * Beware: Don't call before oo.inheritClass.
125 * function Context() {}
127 * // Avoid repeating this code
128 * function ContextLazyLoad() {}
129 * ContextLazyLoad.prototype.getContext = function () {
130 * if ( !this.context ) {
131 * this.context = new Context();
133 * return this.context;
136 * function FooBar() {}
137 * OO.inheritClass( FooBar, Foo );
138 * OO.mixinClass( FooBar, ContextLazyLoad );
140 * @param {Function} targetFn
141 * @param {Function} originFn
143 oo
.mixinClass = function ( targetFn
, originFn
) {
146 // Copy prototype properties
147 for ( key
in originFn
.prototype ) {
148 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
149 targetFn
.prototype[key
] = originFn
.prototype[key
];
153 // Copy static properties - always initialize both sides
154 targetFn
.static = targetFn
.static || {};
155 if ( originFn
.static ) {
156 for ( key
in originFn
.static ) {
157 if ( hasOwn
.call( originFn
.static, key
) ) {
158 targetFn
.static[key
] = originFn
.static[key
];
162 originFn
.static = {};
169 * Create a new object that is an instance of the same
170 * constructor as the input, inherits from the same object
171 * and contains the same own properties.
173 * This makes a shallow non-recursive copy of own properties.
174 * To create a recursive copy of plain objects, use #copy.
176 * var foo = new Person( mom, dad );
178 * var foo2 = OO.cloneObject( foo );
182 * foo2 !== foo; // true
183 * foo2 instanceof Person; // true
184 * foo2.getAge(); // 21
185 * foo.getAge(); // 22
187 * @param {Object} origin
188 * @return {Object} Clone of origin
190 oo
.cloneObject = function ( origin
) {
193 r
= Object
.create( origin
.constructor.prototype );
195 for ( key
in origin
) {
196 if ( hasOwn
.call( origin
, key
) ) {
197 r
[key
] = origin
[key
];
205 * Get an array of all property values in an object.
207 * @param {Object} Object to get values from
208 * @return {Array} List of object values
210 oo
.getObjectValues = function ( obj
) {
213 if ( obj
!== Object( obj
) ) {
214 throw new TypeError( 'Called on non-object' );
219 if ( hasOwn
.call( obj
, key
) ) {
220 values
[values
.length
] = obj
[key
];
228 * Recursively compares properties between two objects.
230 * A false result may be caused by property inequality or by properties in one object missing from
231 * the other. An asymmetrical test may also be performed, which checks only that properties in the
232 * first object are present in the second object, but not the inverse.
234 * @param {Object} a First object to compare
235 * @param {Object} b Second object to compare
236 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
237 * @return {boolean} If the objects contain the same values as each other
239 oo
.compare = function ( a
, b
, asymmetrical
) {
240 var aValue
, bValue
, aType
, bType
, k
;
249 aType
= typeof aValue
;
250 bType
= typeof bValue
;
251 if ( aType
!== bType
||
252 ( ( aType
=== 'string' || aType
=== 'number' ) && aValue
!== bValue
) ||
253 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
257 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
258 return asymmetrical
? true : oo
.compare( b
, a
, true );
262 * Create a plain deep copy of any kind of object.
264 * Copies are deep, and will either be an object or an array depending on `source`.
266 * @param {Object} source Object to copy
267 * @param {Function} [callback] Applied to leaf values before they added to the clone
268 * @return {Object} Copy of source object
270 oo
.copy = function ( source
, callback
) {
271 var key
, sourceValue
, sourceType
, destination
;
273 if ( typeof source
.clone
=== 'function' ) {
274 return source
.clone();
277 destination
= Array
.isArray( source
) ? new Array( source
.length
) : {};
279 for ( key
in source
) {
280 sourceValue
= source
[key
];
281 sourceType
= typeof sourceValue
;
282 if ( Array
.isArray( sourceValue
) ) {
284 destination
[key
] = oo
.copy( sourceValue
, callback
);
285 } else if ( sourceValue
&& typeof sourceValue
.clone
=== 'function' ) {
286 // Duck type object with custom clone method
287 destination
[key
] = callback
?
288 callback( sourceValue
.clone() ) : sourceValue
.clone();
289 } else if ( sourceValue
&& typeof sourceValue
.cloneNode
=== 'function' ) {
291 destination
[key
] = callback
?
292 callback( sourceValue
.cloneNode( true ) ) : sourceValue
.cloneNode( true );
293 } else if ( oo
.isPlainObject( sourceValue
) ) {
295 destination
[key
] = oo
.copy( sourceValue
, callback
);
297 // Non-plain objects (incl. functions) and primitive values
298 destination
[key
] = callback
? callback( sourceValue
) : sourceValue
;
306 * Generate a hash of an object based on its name and data.
308 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
310 * To avoid two objects with the same values generating different hashes, we utilize the replacer
311 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
312 * not be the fastest way to do this; we should investigate this further.
314 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
315 * function, we call that function and use its return value rather than hashing the object
316 * ourselves. This allows classes to define custom hashing.
318 * @param {Object} val Object to generate hash for
319 * @return {string} Hash of object
321 oo
.getHash = function ( val
) {
322 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
326 * Helper function for OO.getHash which sorts objects by key.
328 * This is a callback passed into JSON.stringify.
330 * @method getHash_keySortReplacer
331 * @param {string} key Property name of value being replaced
332 * @param {Mixed} val Property value to replace
333 * @return {Mixed} Replacement value
335 oo
.getHash
.keySortReplacer = function ( key
, val
) {
336 var normalized
, keys
, i
, len
;
337 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
338 // This object has its own custom hash function, use it
339 val
= val
.getHashObject();
341 if ( !Array
.isArray( val
) && Object( val
) === val
) {
342 // Only normalize objects when the key-order is ambiguous
343 // (e.g. any object not an array).
345 keys
= Object
.keys( val
).sort();
348 for ( ; i
< len
; i
+= 1 ) {
349 normalized
[keys
[i
]] = val
[keys
[i
]];
353 // Primitive values and arrays get stable hashes
354 // by default. Lets those be stringified as-is.
361 * Compute the union (duplicate-free merge) of a set of arrays.
363 * Arrays values must be convertable to object keys (strings).
365 * By building an object (with the values for keys) in parallel with
366 * the array, a new item's existence in the union can be computed faster.
368 * @param {Array...} arrays Arrays to union
369 * @return {Array} Union of the arrays
371 oo
.simpleArrayUnion = function () {
372 var i
, ilen
, arr
, j
, jlen
,
376 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
378 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
379 if ( !obj
[ arr
[j
] ] ) {
380 obj
[ arr
[j
] ] = true;
381 result
.push( arr
[j
] );
390 * Combine arrays (intersection or difference).
392 * An intersection checks the item exists in 'b' while difference checks it doesn't.
394 * Arrays values must be convertable to object keys (strings).
396 * By building an object (with the values for keys) of 'b' we can
397 * compute the result faster.
400 * @param {Array} a First array
401 * @param {Array} b Second array
402 * @param {boolean} includeB Whether to items in 'b'
403 * @return {Array} Combination (intersection or difference) of arrays
405 function simpleArrayCombine( a
, b
, includeB
) {
410 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
414 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
415 isInB
= !!bObj
[ a
[i
] ];
416 if ( isInB
=== includeB
) {
425 * Compute the intersection of two arrays (items in both arrays).
427 * Arrays values must be convertable to object keys (strings).
429 * @param {Array} a First array
430 * @param {Array} b Second array
431 * @return {Array} Intersection of arrays
433 oo
.simpleArrayIntersection = function ( a
, b
) {
434 return simpleArrayCombine( a
, b
, true );
438 * Compute the difference of two arrays (items in 'a' but not 'b').
440 * Arrays values must be convertable to object keys (strings).
442 * @param {Array} a First array
443 * @param {Array} b Second array
444 * @return {Array} Intersection of arrays
446 oo
.simpleArrayDifference = function ( a
, b
) {
447 return simpleArrayCombine( a
, b
, false );
450 * @class OO.EventEmitter
454 oo
.EventEmitter
= function OoEventEmitter() {
458 * Storage of bound event handlers by event name.
468 * Add a listener to events of a specific event.
470 * If the callback/context are already bound to the event, they will not be bound again.
472 * @param {string} event Type of event to listen to
473 * @param {Function} callback Function to call when event occurs
474 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
475 * @param {Object} [context=null] Object to use as context for callback function or call method on
476 * @throws {Error} Listener argument is not a function or method name
479 oo
.EventEmitter
.prototype.on = function ( event
, callback
, args
, context
) {
480 var i
, bindings
, binding
;
483 if ( typeof callback
!== 'function' ) {
484 throw new Error( 'Invalid callback. Function or method name expected.' );
486 // Fallback to null context
487 if ( arguments
.length
< 4 ) {
490 if ( this.bindings
.hasOwnProperty( event
) ) {
491 // Check for duplicate callback and context for this event
492 bindings
= this.bindings
[event
];
495 binding
= bindings
[i
];
496 if ( bindings
.callback
=== callback
&& bindings
.context
=== context
) {
501 // Auto-initialize bindings list
502 bindings
= this.bindings
[event
] = [];
514 * Adds a one-time listener to a specific event.
516 * @param {string} event Type of event to listen to
517 * @param {Function} listener Listener to call when event occurs
520 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
521 var eventEmitter
= this;
522 return this.on( event
, function listenerWrapper() {
523 eventEmitter
.off( event
, listenerWrapper
);
524 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
529 * Remove a specific listener from a specific event.
531 * @param {string} event Type of event to remove listener from
532 * @param {Function} [callback] Listener to remove, omit to remove all
533 * @param {Object} [context=null] Object used context for callback function or method
535 * @throws {Error} Listener argument is not a function
537 oo
.EventEmitter
.prototype.off = function ( event
, callback
, context
) {
540 if ( arguments
.length
=== 1 ) {
541 // Remove all bindings for event
542 if ( event
in this.bindings
) {
543 delete this.bindings
[event
];
546 if ( typeof callback
!== 'function' ) {
547 throw new Error( 'Invalid callback. Function expected.' );
549 if ( !( event
in this.bindings
) || !this.bindings
[event
].length
) {
550 // No matching bindings
553 // Fallback to null context
554 if ( arguments
.length
< 3 ) {
557 // Remove matching handlers
558 bindings
= this.bindings
[event
];
561 if ( bindings
[i
].callback
=== callback
&& bindings
[i
].context
=== context
) {
562 bindings
.splice( i
, 1 );
565 // Cleanup if now empty
566 if ( bindings
.length
=== 0 ) {
567 delete this.bindings
[event
];
576 * TODO: Should this be chainable? What is the usefulness of the boolean
579 * @param {string} event Type of event
580 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
581 * @return {boolean} If event was handled by at least one listener
583 oo
.EventEmitter
.prototype.emit = function ( event
) {
584 var i
, len
, binding
, bindings
, args
;
586 if ( event
in this.bindings
) {
587 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
588 bindings
= this.bindings
[event
].slice();
589 args
= Array
.prototype.slice
.call( arguments
, 1 );
590 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
591 binding
= bindings
[i
];
592 binding
.callback
.apply(
594 binding
.args
? binding
.args
.concat( args
) : args
603 * Connect event handlers to an object.
605 * @param {Object} context Object to call methods on when events occur
606 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
607 * event bindings keyed by event name containing either method names, functions or arrays containing
608 * method name or function followed by a list of arguments to be passed to callback before emitted
612 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
613 var method
, callback
, args
, event
;
615 for ( event
in methods
) {
616 method
= methods
[event
];
617 // Allow providing additional args
618 if ( Array
.isArray( method
) ) {
619 args
= method
.slice( 1 );
624 // Allow callback to be a method name
625 if ( typeof method
=== 'string' ) {
627 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
628 throw new Error( 'Method not found: ' + method
);
630 // Resolve to function
631 callback
= context
[method
];
636 this.on
.apply( this, [ event
, callback
, args
, context
] );
642 * Disconnect event handlers from an object.
644 * @param {Object} context Object to disconnect methods from
645 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
646 * event bindings keyed by event name containing either method names or functions
649 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
650 var i
, method
, callback
, event
, bindings
;
653 // Remove specific connections to the context
654 for ( event
in methods
) {
655 method
= methods
[event
];
656 if ( typeof method
=== 'string' ) {
658 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
659 throw new Error( 'Method not found: ' + method
);
661 // Resolve to function
662 callback
= context
[method
];
666 this.off( event
, callback
, context
);
669 // Remove all connections to the context
670 for ( event
in this.bindings
) {
671 bindings
= this.bindings
[event
];
674 if ( bindings
[i
].context
=== context
) {
675 this.off( event
, bindings
[i
].callback
, context
);
685 * @mixins OO.EventEmitter
689 oo
.Registry
= function OoRegistry() {
690 // Mixin constructors
691 oo
.EventEmitter
.call( this );
699 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
705 * @param {string} name
706 * @param {Mixed} data
712 * Associate one or more symbolic names with some data.
714 * Only the base name will be registered, overriding any existing entry with the same base name.
716 * @param {string|string[]} name Symbolic name or list of symbolic names
717 * @param {Mixed} data Data to associate with symbolic name
719 * @throws {Error} Name argument must be a string or array
721 oo
.Registry
.prototype.register = function ( name
, data
) {
723 if ( typeof name
=== 'string' ) {
724 this.registry
[name
] = data
;
725 this.emit( 'register', name
, data
);
726 } else if ( Array
.isArray( name
) ) {
727 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
728 this.register( name
[i
], data
);
731 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
736 * Get data for a given symbolic name.
738 * Lookups are done using the base name.
740 * @param {string} name Symbolic name
741 * @return {Mixed|undefined} Data associated with symbolic name
743 oo
.Registry
.prototype.lookup = function ( name
) {
744 return this.registry
[name
];
748 * @extends OO.Registry
752 oo
.Factory
= function OoFactory() {
753 oo
.Factory
.super.call( this );
761 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
766 * Register a constructor with the factory.
768 * Classes must have a static `name` property to be registered.
770 * function MyClass() {};
771 * // Adds a static property to the class defining a symbolic name
772 * MyClass.static = { 'name': 'mine' };
773 * // Registers class with factory, available via symbolic name 'mine'
774 * factory.register( MyClass );
776 * @param {Function} constructor Constructor to use when creating object
777 * @throws {Error} Name must be a string and must not be empty
778 * @throws {Error} Constructor must be a function
780 oo
.Factory
.prototype.register = function ( constructor ) {
783 if ( typeof constructor !== 'function' ) {
784 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
786 name
= constructor.static && constructor.static.name
;
787 if ( typeof name
!== 'string' || name
=== '' ) {
788 throw new Error( 'Name must be a string and must not be empty' );
790 this.entries
.push( name
);
792 oo
.Factory
.super.prototype.register
.call( this, name
, constructor );
796 * Create an object based on a name.
798 * Name is used to look up the constructor to use, while all additional arguments are passed to the
799 * constructor directly, so leaving one out will pass an undefined to the constructor.
801 * @param {string} name Object name
802 * @param {Mixed...} [args] Arguments to pass to the constructor
803 * @return {Object} The new object
804 * @throws {Error} Unknown object name
806 oo
.Factory
.prototype.create = function ( name
) {
807 var args
, obj
, constructor;
809 if ( !this.registry
.hasOwnProperty( name
) ) {
810 throw new Error( 'No class registered by that name: ' + name
);
812 constructor = this.registry
[name
];
814 // Convert arguments to array and shift the first argument (name) off
815 args
= Array
.prototype.slice
.call( arguments
, 1 );
817 // We can't use the "new" operator with .apply directly because apply needs a
818 // context. So instead just do what "new" does: create an object that inherits from
819 // the constructor's prototype (which also makes it an "instanceof" the constructor),
820 // then invoke the constructor with the object as context, and return it (ignoring
821 // the constructor's return value).
822 obj
= Object
.create( constructor.prototype );
823 constructor.apply( obj
, args
);
826 /*jshint node:true */
827 if ( typeof module
!== 'undefined' && module
.exports
) {