2 * OOjs v1.1.10 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: 2015-11-11T16:49:11Z
11 ( function ( global
) {
15 /*exported toString */
18 * Namespace for all classes, static methods and static properties.
23 // Optimisation: Local reference to Object.prototype.hasOwnProperty
24 hasOwn
= oo
.hasOwnProperty
,
25 toString
= oo
.toString
,
26 // Object.create() is impossible to fully polyfill, so don't require it
27 createObject
= Object
.create
|| ( function () {
28 // Reusable constructor function
30 return function ( prototype, properties
) {
32 Empty
.prototype = prototype;
34 if ( properties
&& hasOwn
.call( properties
, 'constructor' ) ) {
35 obj
.constructor = properties
.constructor.value
;
44 * Utility to initialize a class for OO inheritance.
46 * Currently this just initializes an empty static object.
48 * @param {Function} fn
50 oo
.initClass = function ( fn
) {
51 fn
.static = fn
.static || {};
55 * Inherit from prototype to another using Object#create.
57 * 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 * Person.super.apply( this, arguments );
72 * OO.inheritClass( Person, Thing );
73 * Person.static.defaultEyeCount = 2;
74 * Person.prototype.walk = function () {};
77 * Jumper.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;
88 * @param {Function} targetFn
89 * @param {Function} originFn
90 * @throws {Error} If target already inherits from origin
92 oo
.inheritClass = function ( targetFn
, originFn
) {
93 var targetConstructor
;
95 if ( targetFn
.prototype instanceof originFn
) {
96 throw new Error( 'Target already inherits from origin' );
99 targetConstructor
= targetFn
.prototype.constructor;
101 // Using ['super'] instead of .super because 'super' is not supported
102 // by IE 8 and below (bug 63303).
103 // Provide .parent as alias for code supporting older browsers which
104 // allows people to comply with their style guide.
105 targetFn
[ 'super' ] = targetFn
.parent
= originFn
;
107 targetFn
.prototype = createObject( originFn
.prototype, {
108 // Restore constructor property of targetFn
110 value
: targetConstructor
,
117 // Extend static properties - always initialize both sides
118 oo
.initClass( originFn
);
119 targetFn
.static = createObject( originFn
.static );
123 * Copy over *own* prototype properties of a mixin.
125 * The 'constructor' (whether implicit or explicit) is not copied over.
127 * This does not create inheritance to the origin. If you need inheritance,
128 * use OO.inheritClass instead.
130 * Beware: This can redefine a prototype property, call before setting your prototypes.
132 * Beware: Don't call before OO.inheritClass.
135 * function Context() {}
137 * // Avoid repeating this code
138 * function ContextLazyLoad() {}
139 * ContextLazyLoad.prototype.getContext = function () {
140 * if ( !this.context ) {
141 * this.context = new Context();
143 * return this.context;
146 * function FooBar() {}
147 * OO.inheritClass( FooBar, Foo );
148 * OO.mixinClass( FooBar, ContextLazyLoad );
150 * @param {Function} targetFn
151 * @param {Function} originFn
153 oo
.mixinClass = function ( targetFn
, originFn
) {
156 // Copy prototype properties
157 for ( key
in originFn
.prototype ) {
158 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
159 targetFn
.prototype[ key
] = originFn
.prototype[ key
];
163 // Copy static properties - always initialize both sides
164 oo
.initClass( targetFn
);
165 if ( originFn
.static ) {
166 for ( key
in originFn
.static ) {
167 if ( hasOwn
.call( originFn
.static, key
) ) {
168 targetFn
.static[ key
] = originFn
.static[ key
];
172 oo
.initClass( originFn
);
179 * Get a deeply nested property of an object using variadic arguments, protecting against
180 * undefined property errors.
182 * `quux = oo.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
183 * except that the former protects against JS errors if one of the intermediate properties
184 * is undefined. Instead of throwing an error, this function will return undefined in
187 * @param {Object} obj
188 * @param {...Mixed} [keys]
189 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
191 oo
.getProp = function ( obj
) {
194 for ( i
= 1; i
< arguments
.length
; i
++ ) {
195 if ( retval
=== undefined || retval
=== null ) {
196 // Trying to access a property of undefined or null causes an error
199 retval
= retval
[ arguments
[ i
] ];
205 * Set a deeply nested property of an object using variadic arguments, protecting against
206 * undefined property errors.
208 * `oo.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
209 * the former protects against JS errors if one of the intermediate properties is
210 * undefined. Instead of throwing an error, undefined intermediate properties will be
211 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
212 * is not an object, this function will silently abort.
214 * @param {Object} obj
215 * @param {...Mixed} [keys]
216 * @param {Mixed} [value]
218 oo
.setProp = function ( obj
) {
221 if ( Object( obj
) !== obj
) {
224 for ( i
= 1; i
< arguments
.length
- 2; i
++ ) {
225 if ( prop
[ arguments
[ i
] ] === undefined ) {
226 prop
[ arguments
[ i
] ] = {};
228 if ( Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
231 prop
= prop
[ arguments
[ i
] ];
233 prop
[ arguments
[ arguments
.length
- 2 ] ] = arguments
[ arguments
.length
- 1 ];
237 * Create a new object that is an instance of the same
238 * constructor as the input, inherits from the same object
239 * and contains the same own properties.
241 * This makes a shallow non-recursive copy of own properties.
242 * To create a recursive copy of plain objects, use #copy.
244 * var foo = new Person( mom, dad );
246 * var foo2 = OO.cloneObject( foo );
250 * foo2 !== foo; // true
251 * foo2 instanceof Person; // true
252 * foo2.getAge(); // 21
253 * foo.getAge(); // 22
255 * @param {Object} origin
256 * @return {Object} Clone of origin
258 oo
.cloneObject = function ( origin
) {
261 r
= createObject( origin
.constructor.prototype );
263 for ( key
in origin
) {
264 if ( hasOwn
.call( origin
, key
) ) {
265 r
[ key
] = origin
[ key
];
273 * Get an array of all property values in an object.
275 * @param {Object} obj Object to get values from
276 * @return {Array} List of object values
278 oo
.getObjectValues = function ( obj
) {
281 if ( obj
!== Object( obj
) ) {
282 throw new TypeError( 'Called on non-object' );
287 if ( hasOwn
.call( obj
, key
) ) {
288 values
[ values
.length
] = obj
[ key
];
296 * Use binary search to locate an element in a sorted array.
298 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
299 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
300 * below 0 if it is to the left of elem, or zero if it's equal to elem.
302 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
303 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
304 * `searchFunc = cmp.bind( null, value )`.
306 * @param {Array} arr Array to search in
307 * @param {Function} searchFunc Search function
308 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
309 * @return {number|null} Index where val was found, or null if not found
311 oo
.binarySearch = function ( arr
, searchFunc
, forInsertion
) {
315 while ( left
< right
) {
316 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
317 /*jshint bitwise:false */
318 mid
= ( left
+ right
) >> 1;
319 cmpResult
= searchFunc( arr
[ mid
] );
320 if ( cmpResult
< 0 ) {
322 } else if ( cmpResult
> 0 ) {
328 return forInsertion
? right
: null;
332 * Recursively compare properties between two objects.
334 * A false result may be caused by property inequality or by properties in one object missing from
335 * the other. An asymmetrical test may also be performed, which checks only that properties in the
336 * first object are present in the second object, but not the inverse.
338 * If either a or b is null or undefined it will be treated as an empty object.
340 * @param {Object|undefined|null} a First object to compare
341 * @param {Object|undefined|null} b Second object to compare
342 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
343 * (i.e. a is a subset of b)
344 * @return {boolean} If the objects contain the same values as each other
346 oo
.compare = function ( a
, b
, asymmetrical
) {
347 var aValue
, bValue
, aType
, bType
, k
;
356 if ( typeof a
.nodeType
=== 'number' && typeof a
.isEqualNode
=== 'function' ) {
357 return a
.isEqualNode( b
);
361 if ( !hasOwn
.call( a
, k
) || a
[ k
] === undefined || a
[ k
] === b
[ k
] ) {
362 // Support es3-shim: Without the hasOwn filter, comparing [] to {} will be false in ES3
363 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
364 // Also ignore undefined values, because there is no conceptual difference between
365 // a key that is absent and a key that is present but whose value is undefined.
371 aType
= typeof aValue
;
372 bType
= typeof bValue
;
373 if ( aType
!== bType
||
375 ( aType
=== 'string' || aType
=== 'number' || aType
=== 'boolean' ) &&
378 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, true ) ) ) {
382 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
383 return asymmetrical
? true : oo
.compare( b
, a
, true );
387 * Create a plain deep copy of any kind of object.
389 * Copies are deep, and will either be an object or an array depending on `source`.
391 * @param {Object} source Object to copy
392 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
393 * @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.
394 * @return {Object} Copy of source object
396 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
397 var key
, destination
;
399 if ( nodeCallback
) {
400 // Extensibility: check before attempting to clone source.
401 destination
= nodeCallback( source
);
402 if ( destination
!== undefined ) {
407 if ( Array
.isArray( source
) ) {
408 // Array (fall through)
409 destination
= new Array( source
.length
);
410 } else if ( source
&& typeof source
.clone
=== 'function' ) {
411 // Duck type object with custom clone method
412 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
413 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
415 return leafCallback
?
416 leafCallback( source
.cloneNode( true ) ) :
417 source
.cloneNode( true );
418 } else if ( oo
.isPlainObject( source
) ) {
419 // Plain objects (fall through)
422 // Non-plain objects (incl. functions) and primitive values
423 return leafCallback
? leafCallback( source
) : source
;
426 // source is an array or a plain object
427 for ( key
in source
) {
428 destination
[ key
] = oo
.copy( source
[ key
], leafCallback
, nodeCallback
);
431 // This is an internal node, so we don't apply the leafCallback.
436 * Generate a hash of an object based on its name and data.
438 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
440 * To avoid two objects with the same values generating different hashes, we utilize the replacer
441 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
442 * not be the fastest way to do this; we should investigate this further.
444 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
445 * function, we call that function and use its return value rather than hashing the object
446 * ourselves. This allows classes to define custom hashing.
448 * @param {Object} val Object to generate hash for
449 * @return {string} Hash of object
451 oo
.getHash = function ( val
) {
452 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
456 * Sort objects by key (helper function for OO.getHash).
458 * This is a callback passed into JSON.stringify.
460 * @method getHash_keySortReplacer
461 * @param {string} key Property name of value being replaced
462 * @param {Mixed} val Property value to replace
463 * @return {Mixed} Replacement value
465 oo
.getHash
.keySortReplacer = function ( key
, val
) {
466 var normalized
, keys
, i
, len
;
467 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
468 // This object has its own custom hash function, use it
469 val
= val
.getHashObject();
471 if ( !Array
.isArray( val
) && Object( val
) === val
) {
472 // Only normalize objects when the key-order is ambiguous
473 // (e.g. any object not an array).
475 keys
= Object
.keys( val
).sort();
478 for ( ; i
< len
; i
+= 1 ) {
479 normalized
[ keys
[ i
] ] = val
[ keys
[ i
] ];
483 // Primitive values and arrays get stable hashes
484 // by default. Lets those be stringified as-is.
491 * Get the unique values of an array, removing duplicates
493 * @param {Array} arr Array
494 * @return {Array} Unique values in array
496 oo
.unique = function ( arr
) {
497 return arr
.reduce( function ( result
, current
) {
498 if ( result
.indexOf( current
) === -1 ) {
499 result
.push( current
);
506 * Compute the union (duplicate-free merge) of a set of arrays.
508 * Arrays values must be convertable to object keys (strings).
510 * By building an object (with the values for keys) in parallel with
511 * the array, a new item's existence in the union can be computed faster.
513 * @param {...Array} arrays Arrays to union
514 * @return {Array} Union of the arrays
516 oo
.simpleArrayUnion = function () {
517 var i
, ilen
, arr
, j
, jlen
,
521 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
522 arr
= arguments
[ i
];
523 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
524 if ( !obj
[ arr
[ j
] ] ) {
525 obj
[ arr
[ j
] ] = true;
526 result
.push( arr
[ j
] );
535 * Combine arrays (intersection or difference).
537 * An intersection checks the item exists in 'b' while difference checks it doesn't.
539 * Arrays values must be convertable to object keys (strings).
541 * By building an object (with the values for keys) of 'b' we can
542 * compute the result faster.
545 * @param {Array} a First array
546 * @param {Array} b Second array
547 * @param {boolean} includeB Whether to items in 'b'
548 * @return {Array} Combination (intersection or difference) of arrays
550 function simpleArrayCombine( a
, b
, includeB
) {
555 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
556 bObj
[ b
[ i
] ] = true;
559 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
560 isInB
= !!bObj
[ a
[ i
] ];
561 if ( isInB
=== includeB
) {
562 result
.push( a
[ i
] );
570 * Compute the intersection of two arrays (items in both arrays).
572 * Arrays values must be convertable to object keys (strings).
574 * @param {Array} a First array
575 * @param {Array} b Second array
576 * @return {Array} Intersection of arrays
578 oo
.simpleArrayIntersection = function ( a
, b
) {
579 return simpleArrayCombine( a
, b
, true );
583 * Compute the difference of two arrays (items in 'a' but not 'b').
585 * Arrays values must be convertable to object keys (strings).
587 * @param {Array} a First array
588 * @param {Array} b Second array
589 * @return {Array} Intersection of arrays
591 oo
.simpleArrayDifference = function ( a
, b
) {
592 return simpleArrayCombine( a
, b
, false );
597 oo
.isPlainObject
= $.isPlainObject
;
604 * @class OO.EventEmitter
608 oo
.EventEmitter
= function OoEventEmitter() {
612 * Storage of bound event handlers by event name.
619 oo
.initClass( oo
.EventEmitter
);
621 /* Private helper functions */
624 * Validate a function or method call in a context
626 * For a method name, check that it names a function in the context object
629 * @param {Function|string} method Function or method name
630 * @param {Mixed} context The context of the call
631 * @throws {Error} A method name is given but there is no context
632 * @throws {Error} In the context object, no property exists with the given name
633 * @throws {Error} In the context object, the named property is not a function
635 function validateMethod( method
, context
) {
636 // Validate method and context
637 if ( typeof method
=== 'string' ) {
639 if ( context
=== undefined || context
=== null ) {
640 throw new Error( 'Method name "' + method
+ '" has no context.' );
642 if ( typeof context
[ method
] !== 'function' ) {
643 // Technically the property could be replaced by a function before
644 // call time. But this probably signals a typo.
645 throw new Error( 'Property "' + method
+ '" is not a function' );
647 } else if ( typeof method
!== 'function' ) {
648 throw new Error( 'Invalid callback. Function or method name expected.' );
655 * Add a listener to events of a specific event.
657 * The listener can be a function or the string name of a method; if the latter, then the
658 * name lookup happens at the time the listener is called.
660 * @param {string} event Type of event to listen to
661 * @param {Function|string} method Function or method name to call when event occurs
662 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
663 * @param {Object} [context=null] Context object for function or method call
664 * @throws {Error} Listener argument is not a function or a valid method name
667 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
670 validateMethod( method
, context
);
672 if ( hasOwn
.call( this.bindings
, event
) ) {
673 bindings
= this.bindings
[ event
];
675 // Auto-initialize bindings list
676 bindings
= this.bindings
[ event
] = [];
682 context
: ( arguments
.length
< 4 ) ? null : context
688 * Add a one-time listener to a specific event.
690 * @param {string} event Type of event to listen to
691 * @param {Function} listener Listener to call when event occurs
694 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
695 var eventEmitter
= this,
696 wrapper = function () {
697 eventEmitter
.off( event
, wrapper
);
698 return listener
.apply( this, arguments
);
700 return this.on( event
, wrapper
);
704 * Remove a specific listener from a specific event.
706 * @param {string} event Type of event to remove listener from
707 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
708 * to "on". Omit to remove all listeners.
709 * @param {Object} [context=null] Context object function or method call
711 * @throws {Error} Listener argument is not a function or a valid method name
713 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
716 if ( arguments
.length
=== 1 ) {
717 // Remove all bindings for event
718 delete this.bindings
[ event
];
722 validateMethod( method
, context
);
724 if ( !hasOwn
.call( this.bindings
, event
) || !this.bindings
[ event
].length
) {
725 // No matching bindings
729 // Default to null context
730 if ( arguments
.length
< 3 ) {
734 // Remove matching handlers
735 bindings
= this.bindings
[ event
];
738 if ( bindings
[ i
].method
=== method
&& bindings
[ i
].context
=== context
) {
739 bindings
.splice( i
, 1 );
743 // Cleanup if now empty
744 if ( bindings
.length
=== 0 ) {
745 delete this.bindings
[ event
];
753 * @param {string} event Type of event
754 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
755 * @return {boolean} Whether the event was handled by at least one listener
757 oo
.EventEmitter
.prototype.emit = function ( event
) {
759 i
, len
, binding
, bindings
, method
;
761 if ( hasOwn
.call( this.bindings
, event
) ) {
762 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
763 bindings
= this.bindings
[ event
].slice();
764 for ( i
= 1, len
= arguments
.length
; i
< len
; i
++ ) {
765 args
.push( arguments
[ i
] );
767 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
768 binding
= bindings
[ i
];
769 if ( typeof binding
.method
=== 'string' ) {
770 // Lookup method by name (late binding)
771 method
= binding
.context
[ binding
.method
];
773 method
= binding
.method
;
777 binding
.args
? binding
.args
.concat( args
) : args
786 * Connect event handlers to an object.
788 * @param {Object} context Object to call methods on when events occur
789 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
790 * event bindings keyed by event name containing either method names, functions or arrays containing
791 * method name or function followed by a list of arguments to be passed to callback before emitted
795 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
796 var method
, args
, event
;
798 for ( event
in methods
) {
799 method
= methods
[ event
];
800 // Allow providing additional args
801 if ( Array
.isArray( method
) ) {
802 args
= method
.slice( 1 );
803 method
= method
[ 0 ];
808 this.on( event
, method
, args
, context
);
814 * Disconnect event handlers from an object.
816 * @param {Object} context Object to disconnect methods from
817 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
818 * event bindings keyed by event name. Values can be either method names or functions, but must be
819 * consistent with those used in the corresponding call to "connect".
822 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
823 var i
, event
, method
, bindings
;
826 // Remove specific connections to the context
827 for ( event
in methods
) {
828 method
= methods
[ event
];
829 if ( Array
.isArray( method
) ) {
830 method
= method
[ 0 ];
832 this.off( event
, method
, context
);
835 // Remove all connections to the context
836 for ( event
in this.bindings
) {
837 bindings
= this.bindings
[ event
];
840 // bindings[i] may have been removed by the previous step's
841 // this.off so check it still exists
842 if ( bindings
[ i
] && bindings
[ i
].context
=== context
) {
843 this.off( event
, bindings
[ i
].method
, context
);
857 * Contain and manage a list of OO.EventEmitter items.
859 * Aggregates and manages their events collectively.
861 * This mixin must be used in a class that also mixes in OO.EventEmitter.
864 * @class OO.EmitterList
867 oo
.EmitterList
= function OoEmitterList() {
869 this.aggregateItemEvents
= {};
875 * Item has been added
878 * @param {OO.EventEmitter} item Added item
879 * @param {number} index Index items were added at
883 * Item has been moved to a new index
886 * @param {OO.EventEmitter} item Moved item
887 * @param {number} index Index item was moved to
888 * @param {number} oldIndex The original index the item was in
892 * Item has been removed
895 * @param {OO.EventEmitter} item Removed item
896 * @param {number} index Index the item was removed from
900 * @event clear The list has been cleared of items
906 * Normalize requested index to fit into the bounds of the given array.
910 * @param {Array} arr Given array
911 * @param {number|undefined} index Requested index
912 * @return {number} Normalized index
914 function normalizeArrayIndex( arr
, index
) {
915 return ( index
=== undefined || index
< 0 || index
>= arr
.length
) ?
923 * @return {OO.EventEmitter[]} Items in the list
925 oo
.EmitterList
.prototype.getItems = function () {
926 return this.items
.slice( 0 );
930 * Get the index of a specific item.
932 * @param {OO.EventEmitter} item Requested item
933 * @return {number} Index of the item
935 oo
.EmitterList
.prototype.getItemIndex = function ( item
) {
936 return this.items
.indexOf( item
);
940 * Get number of items.
942 * @return {number} Number of items in the list
944 oo
.EmitterList
.prototype.getItemCount = function () {
945 return this.items
.length
;
949 * Check if a list contains no items.
951 * @return {boolean} Group is empty
953 oo
.EmitterList
.prototype.isEmpty = function () {
954 return !this.items
.length
;
958 * Aggregate the events emitted by the group.
960 * When events are aggregated, the group will listen to all contained items for the event,
961 * and then emit the event under a new name. The new event will contain an additional leading
962 * parameter containing the item that emitted the original event. Other arguments emitted from
963 * the original event are passed through.
965 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
966 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
967 * A `null` value will remove aggregated events.
969 * @throws {Error} If aggregation already exists
971 oo
.EmitterList
.prototype.aggregate = function ( events
) {
972 var i
, item
, add
, remove
, itemEvent
, groupEvent
;
974 for ( itemEvent
in events
) {
975 groupEvent
= events
[ itemEvent
];
977 // Remove existing aggregated event
978 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
979 // Don't allow duplicate aggregations
981 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
983 // Remove event aggregation from existing items
984 for ( i
= 0; i
< this.items
.length
; i
++ ) {
985 item
= this.items
[ i
];
986 if ( item
.connect
&& item
.disconnect
) {
988 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
989 item
.disconnect( this, remove
);
992 // Prevent future items from aggregating event
993 delete this.aggregateItemEvents
[ itemEvent
];
996 // Add new aggregate event
998 // Make future items aggregate event
999 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
1000 // Add event aggregation to existing items
1001 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1002 item
= this.items
[ i
];
1003 if ( item
.connect
&& item
.disconnect
) {
1005 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
1006 item
.connect( this, add
);
1014 * Add items to the list.
1016 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1017 * an array of items to add
1018 * @param {number} [index] Index to add items at. If no index is
1019 * given, or if the index that is given is invalid, the item
1020 * will be added at the end of the list.
1025 oo
.EmitterList
.prototype.addItems = function ( items
, index
) {
1028 if ( !Array
.isArray( items
) ) {
1032 if ( items
.length
=== 0 ) {
1036 index
= normalizeArrayIndex( this.items
, index
);
1037 for ( i
= 0; i
< items
.length
; i
++ ) {
1038 oldIndex
= this.items
.indexOf( items
[ i
] );
1039 if ( oldIndex
!== -1 ) {
1040 // Move item to new index
1041 index
= this.moveItem( items
[ i
], index
);
1042 this.emit( 'move', items
[ i
], index
, oldIndex
);
1044 // insert item at index
1045 index
= this.insertItem( items
[ i
], index
);
1046 this.emit( 'add', items
[ i
], index
);
1055 * Move an item from its current position to a new index.
1057 * The item is expected to exist in the list. If it doesn't,
1058 * the method will throw an exception.
1061 * @param {OO.EventEmitter} item Items to add
1062 * @param {number} newIndex Index to move the item to
1063 * @return {number} The index the item was moved to
1064 * @throws {Error} If item is not in the list
1066 oo
.EmitterList
.prototype.moveItem = function ( item
, newIndex
) {
1067 var existingIndex
= this.items
.indexOf( item
);
1069 if ( existingIndex
=== -1 ) {
1070 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1073 newIndex
= normalizeArrayIndex( this.items
, newIndex
);
1075 // Remove the item from the current index
1076 this.items
.splice( existingIndex
, 1 );
1078 // Adjust new index after removal
1081 // Move the item to the new index
1082 this.items
.splice( newIndex
, 0, item
);
1088 * Utility method to insert an item into the list, and
1089 * connect it to aggregate events.
1091 * Don't call this directly unless you know what you're doing.
1092 * Use #addItems instead.
1095 * @param {OO.EventEmitter} item Items to add
1096 * @param {number} index Index to add items at
1097 * @return {number} The index the item was added at
1099 oo
.EmitterList
.prototype.insertItem = function ( item
, index
) {
1102 // Add the item to event aggregation
1103 if ( item
.connect
&& item
.disconnect
) {
1105 for ( event
in this.aggregateItemEvents
) {
1106 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
1108 item
.connect( this, events
);
1111 index
= normalizeArrayIndex( this.items
, index
);
1113 // Insert into items array
1114 this.items
.splice( index
, 0, item
);
1121 * @param {OO.EventEmitter[]} items Items to remove
1125 oo
.EmitterList
.prototype.removeItems = function ( items
) {
1128 if ( !Array
.isArray( items
) ) {
1132 if ( items
.length
=== 0 ) {
1136 // Remove specific items
1137 for ( i
= 0; i
< items
.length
; i
++ ) {
1139 index
= this.items
.indexOf( item
);
1140 if ( index
!== -1 ) {
1141 if ( item
.connect
&& item
.disconnect
) {
1142 // Disconnect all listeners from the item
1143 item
.disconnect( this );
1145 this.items
.splice( index
, 1 );
1146 this.emit( 'remove', item
, index
);
1159 oo
.EmitterList
.prototype.clearItems = function () {
1161 cleared
= this.items
.splice( 0, this.items
.length
);
1163 // Disconnect all items
1164 for ( i
= 0; i
< cleared
.length
; i
++ ) {
1165 item
= cleared
[ i
];
1166 if ( item
.connect
&& item
.disconnect
) {
1167 item
.disconnect( this );
1171 this.emit( 'clear' );
1179 * Manage a sorted list of OO.EmitterList objects.
1181 * The sort order is based on a callback that compares two items. The return value of
1182 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1183 * if a is equal to b. The callback should only return zero if the two objects are
1186 * When an item changes in a way that could affect their sorting behavior, it must
1187 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1189 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1192 * @class OO.SortedEmitterList
1193 * @mixins OO.EmitterList
1195 * @param {Function} sortingCallback Callback that compares two items.
1197 oo
.SortedEmitterList
= function OoSortedEmitterList( sortingCallback
) {
1198 // Mixin constructors
1199 oo
.EmitterList
.call( this );
1201 this.sortingCallback
= sortingCallback
;
1203 // Listen to sortChange event and make sure
1204 // we re-sort the changed item when that happens
1206 sortChange
: 'itemSortChange'
1209 this.connect( this, {
1210 itemSortChange
: 'onItemSortChange'
1214 oo
.mixinClass( oo
.SortedEmitterList
, oo
.EmitterList
);
1219 * An item has changed properties that affect its sort positioning
1223 * @event itemSortChange
1229 * Handle a case where an item changed a property that relates
1230 * to its sorted order
1232 * @param {OO.EventEmitter} item Item in the list
1234 oo
.SortedEmitterList
.prototype.onItemSortChange = function ( item
) {
1236 this.removeItems( item
);
1237 // Re-add the item so it is in the correct place
1238 this.addItems( item
);
1242 * Change the sorting callback for this sorted list.
1244 * The callback receives two items. The return value of callback(a, b) must be less than zero
1245 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1247 * @param {Function} sortingCallback Sorting callback
1249 oo
.SortedEmitterList
.prototype.setSortingCallback = function ( sortingCallback
) {
1250 var items
= this.getItems();
1252 this.sortingCallback
= sortingCallback
;
1256 // Re-add the items in the new order
1257 this.addItems( items
);
1261 * Add items to the sorted list.
1264 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1265 * an array of items to add
1267 oo
.SortedEmitterList
.prototype.addItems = function ( items
) {
1268 var index
, i
, insertionIndex
;
1270 if ( !Array
.isArray( items
) ) {
1274 if ( items
.length
=== 0 ) {
1278 for ( i
= 0; i
< items
.length
; i
++ ) {
1279 // Find insertion index
1280 insertionIndex
= this.findInsertionIndex( items
[ i
] );
1282 // Check if the item exists using the sorting callback
1283 // and remove it first if it exists
1285 // First make sure the insertion index is not at the end
1286 // of the list (which means it does not point to any actual
1288 insertionIndex
<= this.items
.length
&&
1289 // Make sure there actually is an item in this index
1290 this.items
[ insertionIndex
] &&
1291 // The callback returns 0 if the items are equal
1292 this.sortingCallback( this.items
[ insertionIndex
], items
[ i
] ) === 0
1294 // Remove the existing item
1295 this.removeItems( this.items
[ insertionIndex
] );
1298 // Insert item at the insertion index
1299 index
= this.insertItem( items
[ i
], insertionIndex
);
1300 this.emit( 'add', items
[ i
], insertionIndex
);
1307 * Find the index a given item should be inserted at. If the item is already
1308 * in the list, this will return the index where the item currently is.
1310 * @param {OO.EventEmitter} item Items to insert
1311 * @return {number} The index the item should be inserted at
1313 oo
.SortedEmitterList
.prototype.findInsertionIndex = function ( item
) {
1316 return oo
.binarySearch(
1318 // Fake a this.sortingCallback.bind( null, item ) call here
1319 // otherwise this doesn't pass tests in phantomJS
1320 function ( otherItem
) {
1321 return list
.sortingCallback( item
, otherItem
);
1331 * @class OO.Registry
1332 * @mixins OO.EventEmitter
1336 oo
.Registry
= function OoRegistry() {
1337 // Mixin constructors
1338 oo
.EventEmitter
.call( this );
1346 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
1352 * @param {string} name
1353 * @param {Mixed} data
1358 * @param {string} name
1359 * @param {Mixed} data Data removed from registry
1365 * Associate one or more symbolic names with some data.
1367 * Any existing entry with the same name will be overridden.
1369 * @param {string|string[]} name Symbolic name or list of symbolic names
1370 * @param {Mixed} data Data to associate with symbolic name
1372 * @throws {Error} Name argument must be a string or array
1374 oo
.Registry
.prototype.register = function ( name
, data
) {
1376 if ( typeof name
=== 'string' ) {
1377 this.registry
[ name
] = data
;
1378 this.emit( 'register', name
, data
);
1379 } else if ( Array
.isArray( name
) ) {
1380 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1381 this.register( name
[ i
], data
);
1384 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1389 * Remove one or more symbolic names from the registry
1391 * @param {string|string[]} name Symbolic name or list of symbolic names
1393 * @throws {Error} Name argument must be a string or array
1395 oo
.Registry
.prototype.unregister = function ( name
) {
1397 if ( typeof name
=== 'string' ) {
1398 data
= this.lookup( name
);
1399 if ( data
!== undefined ) {
1400 delete this.registry
[ name
];
1401 this.emit( 'unregister', name
, data
);
1403 } else if ( Array
.isArray( name
) ) {
1404 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1405 this.unregister( name
[ i
] );
1408 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1413 * Get data for a given symbolic name.
1415 * @param {string} name Symbolic name
1416 * @return {Mixed|undefined} Data associated with symbolic name
1418 oo
.Registry
.prototype.lookup = function ( name
) {
1419 if ( hasOwn
.call( this.registry
, name
) ) {
1420 return this.registry
[ name
];
1424 /*global createObject */
1428 * @extends OO.Registry
1432 oo
.Factory
= function OoFactory() {
1433 // Parent constructor
1434 oo
.Factory
.parent
.call( this );
1439 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
1444 * Register a constructor with the factory.
1446 * Classes must have a static `name` property to be registered.
1448 * function MyClass() {};
1449 * OO.initClass( MyClass );
1450 * // Adds a static property to the class defining a symbolic name
1451 * MyClass.static.name = 'mine';
1452 * // Registers class with factory, available via symbolic name 'mine'
1453 * factory.register( MyClass );
1455 * @param {Function} constructor Constructor to use when creating object
1456 * @throws {Error} Name must be a string and must not be empty
1457 * @throws {Error} Constructor must be a function
1459 oo
.Factory
.prototype.register = function ( constructor ) {
1462 if ( typeof constructor !== 'function' ) {
1463 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1465 name
= constructor.static && constructor.static.name
;
1466 if ( typeof name
!== 'string' || name
=== '' ) {
1467 throw new Error( 'Name must be a string and must not be empty' );
1471 oo
.Factory
.parent
.prototype.register
.call( this, name
, constructor );
1475 * Unregister a constructor from the factory.
1477 * @param {Function} constructor Constructor to unregister
1478 * @throws {Error} Name must be a string and must not be empty
1479 * @throws {Error} Constructor must be a function
1481 oo
.Factory
.prototype.unregister = function ( constructor ) {
1484 if ( typeof constructor !== 'function' ) {
1485 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1487 name
= constructor.static && constructor.static.name
;
1488 if ( typeof name
!== 'string' || name
=== '' ) {
1489 throw new Error( 'Name must be a string and must not be empty' );
1493 oo
.Factory
.parent
.prototype.unregister
.call( this, name
);
1497 * Create an object based on a name.
1499 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1500 * constructor directly, so leaving one out will pass an undefined to the constructor.
1502 * @param {string} name Object name
1503 * @param {...Mixed} [args] Arguments to pass to the constructor
1504 * @return {Object} The new object
1505 * @throws {Error} Unknown object name
1507 oo
.Factory
.prototype.create = function ( name
) {
1510 constructor = this.lookup( name
);
1512 if ( !constructor ) {
1513 throw new Error( 'No class registered by that name: ' + name
);
1516 // Convert arguments to array and shift the first argument (name) off
1517 for ( i
= 1; i
< arguments
.length
; i
++ ) {
1518 args
.push( arguments
[ i
] );
1521 // We can't use the "new" operator with .apply directly because apply needs a
1522 // context. So instead just do what "new" does: create an object that inherits from
1523 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1524 // then invoke the constructor with the object as context, and return it (ignoring
1525 // the constructor's return value).
1526 obj
= createObject( constructor.prototype );
1527 constructor.apply( obj
, args
);
1531 /*jshint node:true */
1532 if ( typeof module
!== 'undefined' && module
.exports
) {
1533 module
.exports
= oo
;