2 * OOjs v1.1.0 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-08-31T21:15:46Z
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
||
256 ( ( aType
=== 'string' || aType
=== 'number' ) && aValue
!== bValue
) ||
257 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, asymmetrical
) ) ) {
261 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
262 return asymmetrical
? true : oo
.compare( b
, a
, true );
266 * Create a plain deep copy of any kind of object.
268 * Copies are deep, and will either be an object or an array depending on `source`.
270 * @param {Object} source Object to copy
271 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
272 * @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.
273 * @return {Object} Copy of source object
275 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
276 var key
, destination
;
278 if ( nodeCallback
) {
279 // Extensibility: check before attempting to clone source.
280 destination
= nodeCallback( source
);
281 if ( destination
!== undefined ) {
286 if ( Array
.isArray( source
) ) {
287 // Array (fall through)
288 destination
= new Array( source
.length
);
289 } else if ( source
&& typeof source
.clone
=== 'function' ) {
290 // Duck type object with custom clone method
291 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
292 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
294 return leafCallback
?
295 leafCallback( source
.cloneNode( true ) ) :
296 source
.cloneNode( true );
297 } else if ( oo
.isPlainObject( source
) ) {
298 // Plain objects (fall through)
301 // Non-plain objects (incl. functions) and primitive values
302 return leafCallback
? leafCallback( source
) : source
;
305 // source is an array or a plain object
306 for ( key
in source
) {
307 destination
[key
] = oo
.copy( source
[key
], leafCallback
, nodeCallback
);
310 // This is an internal node, so we don't apply the leafCallback.
315 * Generate a hash of an object based on its name and data.
317 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
319 * To avoid two objects with the same values generating different hashes, we utilize the replacer
320 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
321 * not be the fastest way to do this; we should investigate this further.
323 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
324 * function, we call that function and use its return value rather than hashing the object
325 * ourselves. This allows classes to define custom hashing.
327 * @param {Object} val Object to generate hash for
328 * @return {string} Hash of object
330 oo
.getHash = function ( val
) {
331 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
335 * Sort objects by key (helper function for OO.getHash).
337 * This is a callback passed into JSON.stringify.
339 * @method getHash_keySortReplacer
340 * @param {string} key Property name of value being replaced
341 * @param {Mixed} val Property value to replace
342 * @return {Mixed} Replacement value
344 oo
.getHash
.keySortReplacer = function ( key
, val
) {
345 var normalized
, keys
, i
, len
;
346 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
347 // This object has its own custom hash function, use it
348 val
= val
.getHashObject();
350 if ( !Array
.isArray( val
) && Object( val
) === val
) {
351 // Only normalize objects when the key-order is ambiguous
352 // (e.g. any object not an array).
354 keys
= Object
.keys( val
).sort();
357 for ( ; i
< len
; i
+= 1 ) {
358 normalized
[keys
[i
]] = val
[keys
[i
]];
362 // Primitive values and arrays get stable hashes
363 // by default. Lets those be stringified as-is.
370 * Compute the union (duplicate-free merge) of a set of arrays.
372 * Arrays values must be convertable to object keys (strings).
374 * By building an object (with the values for keys) in parallel with
375 * the array, a new item's existence in the union can be computed faster.
377 * @param {Array...} arrays Arrays to union
378 * @return {Array} Union of the arrays
380 oo
.simpleArrayUnion = function () {
381 var i
, ilen
, arr
, j
, jlen
,
385 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
387 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
388 if ( !obj
[ arr
[j
] ] ) {
389 obj
[ arr
[j
] ] = true;
390 result
.push( arr
[j
] );
399 * Combine arrays (intersection or difference).
401 * An intersection checks the item exists in 'b' while difference checks it doesn't.
403 * Arrays values must be convertable to object keys (strings).
405 * By building an object (with the values for keys) of 'b' we can
406 * compute the result faster.
409 * @param {Array} a First array
410 * @param {Array} b Second array
411 * @param {boolean} includeB Whether to items in 'b'
412 * @return {Array} Combination (intersection or difference) of arrays
414 function simpleArrayCombine( a
, b
, includeB
) {
419 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
423 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
424 isInB
= !!bObj
[ a
[i
] ];
425 if ( isInB
=== includeB
) {
434 * Compute the intersection of two arrays (items in both arrays).
436 * Arrays values must be convertable to object keys (strings).
438 * @param {Array} a First array
439 * @param {Array} b Second array
440 * @return {Array} Intersection of arrays
442 oo
.simpleArrayIntersection = function ( a
, b
) {
443 return simpleArrayCombine( a
, b
, true );
447 * Compute the difference of two arrays (items in 'a' but not 'b').
449 * Arrays values must be convertable to object keys (strings).
451 * @param {Array} a First array
452 * @param {Array} b Second array
453 * @return {Array} Intersection of arrays
455 oo
.simpleArrayDifference = function ( a
, b
) {
456 return simpleArrayCombine( a
, b
, false );
461 oo
.isPlainObject
= $.isPlainObject
;
468 * @class OO.EventEmitter
472 oo
.EventEmitter
= function OoEventEmitter() {
476 * Storage of bound event handlers by event name.
483 oo
.initClass( oo
.EventEmitter
);
485 /* Private helper functions */
488 * Validate a function or method call in a context
490 * For a method name, check that it names a function in the context object
493 * @param {Function|string} method Function or method name
494 * @param {Mixed} context The context of the call
495 * @throws {Error} A method name is given but there is no context
496 * @throws {Error} In the context object, no property exists with the given name
497 * @throws {Error} In the context object, the named property is not a function
499 function validateMethod( method
, context
) {
500 // Validate method and context
501 if ( typeof method
=== 'string' ) {
503 if ( context
=== undefined || context
=== null ) {
504 throw new Error( 'Method name "' + method
+ '" has no context.' );
506 if ( !( method
in context
) ) {
507 // Technically the method does not need to exist yet: it could be
508 // added before call time. But this probably signals a typo.
509 throw new Error( 'Method not found: "' + method
+ '"' );
511 if ( typeof context
[method
] !== 'function' ) {
512 // Technically the property could be replaced by a function before
513 // call time. But this probably signals a typo.
514 throw new Error( 'Property "' + method
+ '" is not a function' );
516 } else if ( typeof method
!== 'function' ) {
517 throw new Error( 'Invalid callback. Function or method name expected.' );
524 * Add a listener to events of a specific event.
526 * The listener can be a function or the string name of a method; if the latter, then the
527 * name lookup happens at the time the listener is called.
529 * @param {string} event Type of event to listen to
530 * @param {Function|string} method Function or method name to call when event occurs
531 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
532 * @param {Object} [context=null] Context object for function or method call
533 * @throws {Error} Listener argument is not a function or a valid method name
536 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
539 validateMethod( method
, context
);
541 if ( hasOwn
.call( this.bindings
, event
) ) {
542 bindings
= this.bindings
[event
];
544 // Auto-initialize bindings list
545 bindings
= this.bindings
[event
] = [];
551 context
: ( arguments
.length
< 4 ) ? null : context
557 * Add a one-time listener to a specific event.
559 * @param {string} event Type of event to listen to
560 * @param {Function} listener Listener to call when event occurs
563 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
564 var eventEmitter
= this,
565 listenerWrapper = function () {
566 eventEmitter
.off( event
, listenerWrapper
);
567 listener
.apply( eventEmitter
, Array
.prototype.slice
.call( arguments
, 0 ) );
569 return this.on( event
, listenerWrapper
);
573 * Remove a specific listener from a specific event.
575 * @param {string} event Type of event to remove listener from
576 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
577 * to "on". Omit to remove all listeners.
578 * @param {Object} [context=null] Context object function or method call
580 * @throws {Error} Listener argument is not a function or a valid method name
582 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
585 if ( arguments
.length
=== 1 ) {
586 // Remove all bindings for event
587 delete this.bindings
[event
];
591 validateMethod( method
, context
);
593 if ( !( event
in this.bindings
) || !this.bindings
[event
].length
) {
594 // No matching bindings
598 // Default to null context
599 if ( arguments
.length
< 3 ) {
603 // Remove matching handlers
604 bindings
= this.bindings
[event
];
607 if ( bindings
[i
].method
=== method
&& bindings
[i
].context
=== context
) {
608 bindings
.splice( i
, 1 );
612 // Cleanup if now empty
613 if ( bindings
.length
=== 0 ) {
614 delete this.bindings
[event
];
622 * TODO: Should this be chainable? What is the usefulness of the boolean
625 * @param {string} event Type of event
626 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
627 * @return {boolean} If event was handled by at least one listener
629 oo
.EventEmitter
.prototype.emit = function ( event
) {
630 var i
, len
, binding
, bindings
, args
, method
;
632 if ( event
in this.bindings
) {
633 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
634 bindings
= this.bindings
[event
].slice();
635 args
= Array
.prototype.slice
.call( arguments
, 1 );
636 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
637 binding
= bindings
[i
];
638 if ( typeof binding
.method
=== 'string' ) {
639 // Lookup method by name (late binding)
640 method
= binding
.context
[ binding
.method
];
642 method
= binding
.method
;
646 binding
.args
? binding
.args
.concat( args
) : args
655 * Connect event handlers to an object.
657 * @param {Object} context Object to call methods on when events occur
658 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
659 * event bindings keyed by event name containing either method names, functions or arrays containing
660 * method name or function followed by a list of arguments to be passed to callback before emitted
664 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
665 var method
, args
, event
;
667 for ( event
in methods
) {
668 method
= methods
[event
];
669 // Allow providing additional args
670 if ( Array
.isArray( method
) ) {
671 args
= method
.slice( 1 );
677 this.on( event
, method
, args
, context
);
683 * Disconnect event handlers from an object.
685 * @param {Object} context Object to disconnect methods from
686 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
687 * event bindings keyed by event name. Values can be either method names or functions, but must be
688 * consistent with those used in the corresponding call to "connect".
691 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
692 var i
, event
, bindings
;
695 // Remove specific connections to the context
696 for ( event
in methods
) {
697 this.off( event
, methods
[event
], context
);
700 // Remove all connections to the context
701 for ( event
in this.bindings
) {
702 bindings
= this.bindings
[event
];
705 // bindings[i] may have been removed by the previous step's
706 // this.off so check it still exists
707 if ( bindings
[i
] && bindings
[i
].context
=== context
) {
708 this.off( event
, bindings
[i
].method
, context
);
723 * @mixins OO.EventEmitter
727 oo
.Registry
= function OoRegistry() {
728 // Mixin constructors
729 oo
.EventEmitter
.call( this );
737 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
743 * @param {string} name
744 * @param {Mixed} data
750 * Associate one or more symbolic names with some data.
752 * Only the base name will be registered, overriding any existing entry with the same base name.
754 * @param {string|string[]} name Symbolic name or list of symbolic names
755 * @param {Mixed} data Data to associate with symbolic name
757 * @throws {Error} Name argument must be a string or array
759 oo
.Registry
.prototype.register = function ( name
, data
) {
761 if ( typeof name
=== 'string' ) {
762 this.registry
[name
] = data
;
763 this.emit( 'register', name
, data
);
764 } else if ( Array
.isArray( name
) ) {
765 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
766 this.register( name
[i
], data
);
769 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
774 * Get data for a given symbolic name.
776 * Lookups are done using the base name.
778 * @param {string} name Symbolic name
779 * @return {Mixed|undefined} Data associated with symbolic name
781 oo
.Registry
.prototype.lookup = function ( name
) {
782 if ( hasOwn
.call( this.registry
, name
) ) {
783 return this.registry
[name
];
789 * @extends OO.Registry
793 oo
.Factory
= function OoFactory() {
794 oo
.Factory
.parent
.call( this );
802 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
807 * Register a constructor with the factory.
809 * Classes must have a static `name` property to be registered.
811 * function MyClass() {};
812 * OO.initClass( MyClass );
813 * // Adds a static property to the class defining a symbolic name
814 * MyClass.static.name = 'mine';
815 * // Registers class with factory, available via symbolic name 'mine'
816 * factory.register( MyClass );
818 * @param {Function} constructor Constructor to use when creating object
819 * @throws {Error} Name must be a string and must not be empty
820 * @throws {Error} Constructor must be a function
822 oo
.Factory
.prototype.register = function ( constructor ) {
825 if ( typeof constructor !== 'function' ) {
826 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
828 name
= constructor.static && constructor.static.name
;
829 if ( typeof name
!== 'string' || name
=== '' ) {
830 throw new Error( 'Name must be a string and must not be empty' );
832 this.entries
.push( name
);
834 oo
.Factory
.parent
.prototype.register
.call( this, name
, constructor );
838 * Create an object based on a name.
840 * Name is used to look up the constructor to use, while all additional arguments are passed to the
841 * constructor directly, so leaving one out will pass an undefined to the constructor.
843 * @param {string} name Object name
844 * @param {Mixed...} [args] Arguments to pass to the constructor
845 * @return {Object} The new object
846 * @throws {Error} Unknown object name
848 oo
.Factory
.prototype.create = function ( name
) {
850 constructor = this.lookup( name
);
852 if ( !constructor ) {
853 throw new Error( 'No class registered by that name: ' + name
);
856 // Convert arguments to array and shift the first argument (name) off
857 args
= Array
.prototype.slice
.call( arguments
, 1 );
859 // We can't use the "new" operator with .apply directly because apply needs a
860 // context. So instead just do what "new" does: create an object that inherits from
861 // the constructor's prototype (which also makes it an "instanceof" the constructor),
862 // then invoke the constructor with the object as context, and return it (ignoring
863 // the constructor's return value).
864 obj
= Object
.create( constructor.prototype );
865 constructor.apply( obj
, args
);
869 /*jshint node:true */
870 if ( typeof module
!== 'undefined' && module
.exports
) {