2 * OOjs v1.0.7-pre (9c04f3e917)
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: Fri Feb 14 2014 17:51:43 GMT-0800 (PST)
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.
33 oo
.isPlainObject = function ( obj
) {
34 // Any object or value whose internal [[Class]] property is not "[object Object]"
35 if ( toString
.call( obj
) !== '[object Object]' ) {
39 // The try/catch suppresses exceptions thrown when attempting to access
40 // the "constructor" property of certain host objects suich as window.location
41 // in Firefox < 20 (https://bugzilla.mozilla.org/814622)
43 if ( obj
.constructor &&
44 !hasOwn
.call( obj
.constructor.prototype, 'isPrototypeOf' ) ) {
55 * Utility for common usage of Object#create for inheriting from one
56 * prototype to another.
58 * Beware: This redefines the prototype, call before setting your prototypes.
59 * Beware: This redefines the prototype, can only be called once on a function.
60 * If called multiple times on the same function, the previous prototype is lost.
61 * This is how prototypal inheritance works, it can only be one straight chain
62 * (just like classical inheritance in PHP for example). If you need to work with
63 * multiple constructors consider storing an instance of the other constructor in a
64 * property instead, or perhaps use a mixin (see oo.mixinClass).
67 * Thing.prototype.exists = function () {};
70 * this.constructor.super.apply( this, arguments );
72 * oo.inheritClass( Person, Thing );
73 * Person.static.defaultEyeCount = 2;
74 * Person.prototype.walk = function () {};
77 * this.constructor.super.apply( this, arguments );
79 * OO.inheritClass( Jumper, Person );
80 * Jumper.prototype.jump = function () {};
82 * Jumper.static.defaultEyeCount === 2;
83 * var x = new Jumper();
86 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
89 * @param {Function} targetFn
90 * @param {Function} originFn
91 * @throws {Error} If target already inherits from origin
93 oo
.inheritClass = function ( targetFn
, originFn
) {
94 if ( targetFn
.prototype instanceof originFn
) {
95 throw new Error( 'Target already inherits from origin' );
98 var targetConstructor
= targetFn
.prototype.constructor;
100 targetFn
.super = originFn
;
101 targetFn
.prototype = Object
.create( originFn
.prototype, {
102 // Restore constructor property of targetFn
104 value
: targetConstructor
,
111 // Extend static properties - always initialize both sides
112 originFn
.static = originFn
.static || {};
113 targetFn
.static = Object
.create( originFn
.static );
117 * Utility to copy over *own* prototype properties of a mixin.
118 * The 'constructor' (whether implicit or explicit) is not copied over.
120 * This does not create inheritance to the origin. If inheritance is needed
121 * use oo.inheritClass instead.
123 * Beware: This can redefine a prototype property, call before setting your prototypes.
124 * Beware: Don't call before oo.inheritClass.
127 * function Context() {}
129 * // Avoid repeating this code
130 * function ContextLazyLoad() {}
131 * ContextLazyLoad.prototype.getContext = function () {
132 * if ( !this.context ) {
133 * this.context = new Context();
135 * return this.context;
138 * function FooBar() {}
139 * OO.inheritClass( FooBar, Foo );
140 * OO.mixinClass( FooBar, ContextLazyLoad );
143 * @param {Function} targetFn
144 * @param {Function} originFn
146 oo
.mixinClass = function ( targetFn
, originFn
) {
149 // Copy prototype properties
150 for ( key
in originFn
.prototype ) {
151 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
152 targetFn
.prototype[key
] = originFn
.prototype[key
];
156 // Copy static properties - always initialize both sides
157 targetFn
.static = targetFn
.static || {};
158 if ( originFn
.static ) {
159 for ( key
in originFn
.static ) {
160 if ( hasOwn
.call( originFn
.static, key
) ) {
161 targetFn
.static[key
] = originFn
.static[key
];
165 originFn
.static = {};
172 * Create a new object that is an instance of the same
173 * constructor as the input, inherits from the same object
174 * and contains the same own properties.
176 * This makes a shallow non-recursive copy of own properties.
177 * To create a recursive copy of plain objects, use #copy.
179 * var foo = new Person( mom, dad );
181 * var foo2 = OO.cloneObject( foo );
185 * foo2 !== foo; // true
186 * foo2 instanceof Person; // true
187 * foo2.getAge(); // 21
188 * foo.getAge(); // 22
191 * @param {Object} origin
192 * @return {Object} Clone of origin
194 oo
.cloneObject = function ( origin
) {
197 r
= Object
.create( origin
.constructor.prototype );
199 for ( key
in origin
) {
200 if ( hasOwn
.call( origin
, key
) ) {
201 r
[key
] = origin
[key
];
209 * Gets an array of all property values in an object.
212 * @param {Object} Object to get values from
213 * @returns {Array} List of object values
215 oo
.getObjectValues = function ( obj
) {
218 if ( obj
!== Object( obj
) ) {
219 throw new TypeError( 'Called on non-object' );
224 if ( hasOwn
.call( obj
, key
) ) {
225 values
[values
.length
] = obj
[key
];
233 * Recursively compares properties between two objects.
235 * A false result may be caused by property inequality or by properties in one object missing from
236 * the other. An asymmetrical test may also be performed, which checks only that properties in the
237 * first object are present in the second object, but not the inverse.
240 * @param {Object} a First object to compare
241 * @param {Object} b Second object to compare
242 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
243 * @returns {boolean} If the objects contain the same values as each other
245 oo
.compare = function ( a
, b
, asymmetrical
) {
246 var aValue
, bValue
, aType
, bType
, k
;
255 aType
= typeof aValue
;
256 bType
= typeof bValue
;
257 if ( aType
!== bType
||
258 ( ( aType
=== 'string' || aType
=== 'number' ) && aValue
!== bValue
) ||
259 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
263 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
264 return asymmetrical
? true : oo
.compare( b
, a
, true );
268 * Create a plain deep copy of any kind of object.
270 * 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} [callback] Applied to leaf values before they added to the clone
275 * @returns {Object} Copy of source object
277 oo
.copy = function ( source
, callback
) {
278 var key
, sourceValue
, sourceType
, destination
;
280 if ( typeof source
.clone
=== 'function' ) {
281 return source
.clone();
284 destination
= Array
.isArray( source
) ? new Array( source
.length
) : {};
286 for ( key
in source
) {
287 sourceValue
= source
[key
];
288 sourceType
= typeof sourceValue
;
289 if ( Array
.isArray( sourceValue
) ) {
291 destination
[key
] = oo
.copy( sourceValue
, callback
);
292 } else if ( sourceValue
&& typeof sourceValue
.clone
=== 'function' ) {
293 // Duck type object with custom clone method
294 destination
[key
] = callback
?
295 callback( sourceValue
.clone() ) : sourceValue
.clone();
296 } else if ( sourceValue
&& typeof sourceValue
.cloneNode
=== 'function' ) {
298 destination
[key
] = callback
?
299 callback( sourceValue
.cloneNode( true ) ) : sourceValue
.cloneNode( true );
300 } else if ( oo
.isPlainObject( sourceValue
) ) {
302 destination
[key
] = oo
.copy( sourceValue
, callback
);
304 // Non-plain objects (incl. functions) and primitive values
305 destination
[key
] = callback
? callback( sourceValue
) : sourceValue
;
313 * Generates a hash of an object based on its name and data.
314 * Performance optimization: http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse
316 * To avoid two objects with the same values generating different hashes, we utilize the replacer
317 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
318 * not be the fastest way to do this; we should investigate this further.
320 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
321 * function, we call that function and use its return value rather than hashing the object
322 * ourselves. This allows classes to define custom hashing.
324 * @param {Object} val Object to generate hash for
325 * @returns {string} Hash of object
327 oo
.getHash = function ( val
) {
328 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
332 * Helper function for oo.getHash which sorts objects by key.
334 * This is a callback passed into JSON.stringify.
336 * @param {string} key Property name of value being replaced
337 * @param {Mixed} val Property value to replace
338 * @returns {Mixed} Replacement value
340 oo
.getHash
.keySortReplacer = function ( key
, val
) {
341 var normalized
, keys
, i
, len
;
342 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
343 // This object has its own custom hash function, use it
344 val
= val
.getHashObject();
346 if ( !Array
.isArray( val
) && Object( val
) === val
) {
347 // Only normalize objects when the key-order is ambiguous
348 // (e.g. any object not an array).
350 keys
= Object
.keys( val
).sort();
353 for ( ; i
< len
; i
+= 1 ) {
354 normalized
[keys
[i
]] = val
[keys
[i
]];
358 // Primitive values and arrays get stable hashes
359 // by default. Lets those be stringified as-is.
366 * Compute the union (duplicate-free merge) of a set of arrays.
368 * Arrays values must be convertable to object keys (strings)
370 * By building an object (with the values for keys) in parallel with
371 * the array, a new item's existence in the union can be computed faster
373 * @param {Array...} arrays Arrays to union
374 * @returns {Array} Union of the arrays
376 oo
.simpleArrayUnion = function () {
377 var i
, ilen
, arr
, j
, jlen
,
381 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
383 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
384 if ( !obj
[ arr
[j
] ] ) {
385 obj
[ arr
[j
] ] = true;
386 result
.push( arr
[j
] );
395 * Combine arrays (intersection or difference).
397 * An intersection checks the item exists in 'b' while difference checks it doesn't.
399 * Arrays values must be convertable to object keys (strings)
401 * By building an object (with the values for keys) of 'b' we can
402 * compute the result faster
405 * @param {Array} a First array
406 * @param {Array} b Second array
407 * @param {boolean} includeB Whether to items in 'b'
408 * @returns {Array} Combination (intersection or difference) of arrays
410 function simpleArrayCombine( a
, b
, includeB
) {
415 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
419 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
420 isInB
= !!bObj
[ a
[i
] ];
421 if ( isInB
=== includeB
) {
430 * Compute the intersection of two arrays (items in both arrays).
432 * Arrays values must be convertable to object keys (strings)
434 * @param {Array} a First array
435 * @param {Array} b Second array
436 * @returns {Array} Intersection of arrays
438 oo
.simpleArrayIntersection = function ( a
, b
) {
439 return simpleArrayCombine( a
, b
, true );
443 * Compute the difference of two arrays (items in 'a' but not 'b').
445 * Arrays values must be convertable to object keys (strings)
447 * @param {Array} a First array
448 * @param {Array} b Second array
449 * @returns {Array} Intersection of arrays
451 oo
.simpleArrayDifference = function ( a
, b
) {
452 return simpleArrayCombine( a
, b
, false );
457 * @class OO.EventEmitter
460 * @property {Object} bindings
462 oo
.EventEmitter
= function OoEventEmitter() {
470 * Add a listener to events of a specific event.
472 * If the callback/context are already bound to the event, they will not be bound again.
475 * @param {string} event Type of event to listen to
476 * @param {Function} callback Function to call when event occurs
477 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
478 * @param {Object} [context=null] Object to use as context for callback function or call method on
479 * @throws {Error} Listener argument is not a function or method name
482 oo
.EventEmitter
.prototype.on = function ( event
, callback
, args
, context
) {
483 var i
, bindings
, binding
;
486 if ( typeof callback
!== 'function' ) {
487 throw new Error( 'Invalid callback. Function or method name expected.' );
489 // Fallback to null context
490 if ( arguments
.length
< 4 ) {
493 if ( this.bindings
.hasOwnProperty( event
) ) {
494 // Check for duplicate callback and context for this event
495 bindings
= this.bindings
[event
];
498 binding
= bindings
[i
];
499 if ( bindings
.callback
=== callback
&& bindings
.context
=== context
) {
504 // Auto-initialize bindings list
505 bindings
= this.bindings
[event
] = [];
517 * Adds a one-time listener to a specific event.
520 * @param {string} event Type of event to listen to
521 * @param {Function} listener Listener to call when event occurs
524 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
525 var eventEmitter
= this;
526 return this.on( event
, function listenerWrapper() {
527 eventEmitter
.off( event
, listenerWrapper
);
528 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
533 * Remove a specific listener from a specific event.
536 * @param {string} event Type of event to remove listener from
537 * @param {Function} [callback] Listener to remove, omit to remove all
538 * @param {Object} [context=null] Object used context for callback function or method
540 * @throws {Error} Listener argument is not a function
542 oo
.EventEmitter
.prototype.off = function ( event
, callback
, context
) {
545 if ( arguments
.length
=== 1 ) {
546 // Remove all bindings for event
547 if ( event
in this.bindings
) {
548 delete this.bindings
[event
];
551 if ( typeof callback
!== 'function' ) {
552 throw new Error( 'Invalid callback. Function expected.' );
554 if ( !( event
in this.bindings
) || !this.bindings
[event
].length
) {
555 // No matching bindings
558 // Fallback to null context
559 if ( arguments
.length
< 3 ) {
562 // Remove matching handlers
563 bindings
= this.bindings
[event
];
566 if ( bindings
[i
].callback
=== callback
&& bindings
[i
].context
=== context
) {
567 bindings
.splice( i
, 1 );
570 // Cleanup if now empty
571 if ( bindings
.length
=== 0 ) {
572 delete this.bindings
[event
];
580 * TODO: Should this be chainable? What is the usefulness of the boolean
584 * @param {string} event Type of event
585 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
586 * @returns {boolean} If event was handled by at least one listener
588 oo
.EventEmitter
.prototype.emit = function ( event
) {
589 var i
, len
, binding
, bindings
, args
;
591 if ( event
in this.bindings
) {
592 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
593 bindings
= this.bindings
[event
].slice();
594 args
= Array
.prototype.slice
.call( arguments
, 1 );
595 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
596 binding
= bindings
[i
];
597 binding
.callback
.apply(
599 binding
.args
? binding
.args
.concat( args
) : args
608 * Connect event handlers to an object.
611 * @param {Object} context Object to call methods on when events occur
612 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
613 * event bindings keyed by event name containing either method names, functions or arrays containing
614 * method name or function followed by a list of arguments to be passed to callback before emitted
618 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
619 var method
, callback
, args
, event
;
621 for ( event
in methods
) {
622 method
= methods
[event
];
623 // Allow providing additional args
624 if ( Array
.isArray( method
) ) {
625 args
= method
.slice( 1 );
630 // Allow callback to be a method name
631 if ( typeof method
=== 'string' ) {
633 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
634 throw new Error( 'Method not found: ' + method
);
636 // Resolve to function
637 callback
= context
[method
];
642 this.on
.apply( this, [ event
, callback
, args
, context
] );
648 * Disconnect event handlers from an object.
651 * @param {Object} context Object to disconnect methods from
652 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
653 * event bindings keyed by event name containing either method names or functions
656 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
657 var i
, method
, callback
, event
, bindings
;
660 // Remove specific connections to the context
661 for ( event
in methods
) {
662 method
= methods
[event
];
663 if ( typeof method
=== 'string' ) {
665 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
666 throw new Error( 'Method not found: ' + method
);
668 // Resolve to function
669 callback
= context
[method
];
673 this.off( event
, callback
, context
);
676 // Remove all connections to the context
677 for ( event
in this.bindings
) {
678 bindings
= this.bindings
[event
];
681 if ( bindings
[i
].context
=== context
) {
682 this.off( event
, bindings
[i
].callback
, context
);
694 * @mixins OO.EventEmitter
698 oo
.Registry
= function OoRegistry() {
699 // Mixin constructors
700 oo
.EventEmitter
.call( this );
708 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
714 * @param {string} name
715 * @param {Mixed} data
721 * Associate one or more symbolic names with some data.
723 * Only the base name will be registered, overriding any existing entry with the same base name.
726 * @param {string|string[]} name Symbolic name or list of symbolic names
727 * @param {Mixed} data Data to associate with symbolic name
729 * @throws {Error} Name argument must be a string or array
731 oo
.Registry
.prototype.register = function ( name
, data
) {
732 if ( typeof name
!== 'string' && !Array
.isArray( name
) ) {
733 throw new Error( 'Name argument must be a string or array, cannot be a ' + typeof name
);
736 if ( Array
.isArray( name
) ) {
737 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
738 this.register( name
[i
], data
);
740 } else if ( typeof name
=== 'string' ) {
741 this.registry
[name
] = data
;
742 this.emit( 'register', name
, data
);
744 throw new Error( 'Name must be a string or array of strings, cannot be a ' + typeof name
);
749 * Gets data for a given symbolic name.
751 * Lookups are done using the base name.
754 * @param {string} name Symbolic name
755 * @returns {Mixed|undefined} Data associated with symbolic name
757 oo
.Registry
.prototype.lookup = function ( name
) {
758 return this.registry
[name
];
764 * @extends OO.Registry
768 oo
.Factory
= function OoFactory() {
769 // Parent constructor
770 oo
.Registry
.call( this );
778 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
783 * Register a constructor with the factory.
785 * Classes must have a static `name` property to be registered.
788 * function MyClass() {};
789 * // Adds a static property to the class defining a symbolic name
790 * MyClass.static = { 'name': 'mine' };
791 * // Registers class with factory, available via symbolic name 'mine'
792 * factory.register( MyClass );
795 * @param {Function} constructor Constructor to use when creating object
796 * @throws {Error} Name must be a string and must not be empty
797 * @throws {Error} Constructor must be a function
799 oo
.Factory
.prototype.register = function ( constructor ) {
802 if ( typeof constructor !== 'function' ) {
803 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
805 name
= constructor.static && constructor.static.name
;
806 if ( typeof name
!== 'string' || name
=== '' ) {
807 throw new Error( 'Name must be a string and must not be empty' );
809 this.entries
.push( name
);
810 oo
.Registry
.prototype.register
.call( this, name
, constructor );
814 * Create an object based on a name.
816 * Name is used to look up the constructor to use, while all additional arguments are passed to the
817 * constructor directly, so leaving one out will pass an undefined to the constructor.
820 * @param {string} name Object name
821 * @param {Mixed...} [args] Arguments to pass to the constructor
822 * @returns {Object} The new object
823 * @throws {Error} Unknown object name
825 oo
.Factory
.prototype.create = function ( name
) {
826 var args
, obj
, constructor;
828 if ( !this.registry
.hasOwnProperty( name
) ) {
829 throw new Error( 'No class registered by that name: ' + name
);
831 constructor = this.registry
[name
];
833 // Convert arguments to array and shift the first argument (name) off
834 args
= Array
.prototype.slice
.call( arguments
, 1 );
836 // We can't use the "new" operator with .apply directly because apply needs a
837 // context. So instead just do what "new" does: create an object that inherits from
838 // the constructor's prototype (which also makes it an "instanceof" the constructor),
839 // then invoke the constructor with the object as context, and return it (ignoring
840 // the constructor's return value).
841 obj
= Object
.create( constructor.prototype );
842 constructor.apply( obj
, args
);
845 /*jshint node:true */
846 if ( typeof module
!== 'undefined' && module
.exports
) {