Merge "Make LinkCache::isCacheable include namespaces like NS_CATEGORY/NS_MODULE"
[lhc/web/wiklou.git] / resources / lib / oojs / oojs.jquery.js
1 /*!
2 * OOjs v2.2.2 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
4 *
5 * Copyright 2011-2018 OOjs Team and other contributors.
6 * Released under the MIT license
7 * https://oojs.mit-license.org
8 *
9 * Date: 2018-06-14T20:13:14Z
10 */
11 ( function ( global ) {
12
13 'use strict';
14
15 /* exported toString */
16 var
17 /**
18 * Namespace for all classes, static methods and static properties.
19 * @class OO
20 * @singleton
21 */
22 oo = {},
23 // Optimisation: Local reference to Object.prototype.hasOwnProperty
24 hasOwn = oo.hasOwnProperty,
25 toString = oo.toString;
26
27 /* Class Methods */
28
29 /**
30 * Utility to initialize a class for OO inheritance.
31 *
32 * Currently this just initializes an empty static object.
33 *
34 * @param {Function} fn
35 */
36 oo.initClass = function ( fn ) {
37 fn.static = fn.static || {};
38 };
39
40 /**
41 * Inherit from prototype to another using Object#create.
42 *
43 * Beware: This redefines the prototype, call before setting your prototypes.
44 *
45 * Beware: This redefines the prototype, can only be called once on a function.
46 * If called multiple times on the same function, the previous prototype is lost.
47 * This is how prototypal inheritance works, it can only be one straight chain
48 * (just like classical inheritance in PHP for example). If you need to work with
49 * multiple constructors consider storing an instance of the other constructor in a
50 * property instead, or perhaps use a mixin (see OO.mixinClass).
51 *
52 * function Thing() {}
53 * Thing.prototype.exists = function () {};
54 *
55 * function Person() {
56 * Person.super.apply( this, arguments );
57 * }
58 * OO.inheritClass( Person, Thing );
59 * Person.static.defaultEyeCount = 2;
60 * Person.prototype.walk = function () {};
61 *
62 * function Jumper() {
63 * Jumper.super.apply( this, arguments );
64 * }
65 * OO.inheritClass( Jumper, Person );
66 * Jumper.prototype.jump = function () {};
67 *
68 * Jumper.static.defaultEyeCount === 2;
69 * var x = new Jumper();
70 * x.jump();
71 * x.walk();
72 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
73 *
74 * @param {Function} targetFn
75 * @param {Function} originFn
76 * @throws {Error} If target already inherits from origin
77 */
78 oo.inheritClass = function ( targetFn, originFn ) {
79 var targetConstructor;
80
81 if ( !originFn ) {
82 throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn + ')' );
83 }
84 if ( targetFn.prototype instanceof originFn ) {
85 throw new Error( 'inheritClass: Target already inherits from origin' );
86 }
87
88 targetConstructor = targetFn.prototype.constructor;
89
90 // [DEPRECATED] Provide .parent as alias for code supporting older browsers which
91 // allows people to comply with their style guide.
92 targetFn.super = targetFn.parent = originFn;
93
94 targetFn.prototype = Object.create( originFn.prototype, {
95 // Restore constructor property of targetFn
96 constructor: {
97 value: targetConstructor,
98 enumerable: false,
99 writable: true,
100 configurable: true
101 }
102 } );
103
104 // Extend static properties - always initialize both sides
105 oo.initClass( originFn );
106 targetFn.static = Object.create( originFn.static );
107 };
108
109 /**
110 * Copy over *own* prototype properties of a mixin.
111 *
112 * The 'constructor' (whether implicit or explicit) is not copied over.
113 *
114 * This does not create inheritance to the origin. If you need inheritance,
115 * use OO.inheritClass instead.
116 *
117 * Beware: This can redefine a prototype property, call before setting your prototypes.
118 *
119 * Beware: Don't call before OO.inheritClass.
120 *
121 * function Foo() {}
122 * function Context() {}
123 *
124 * // Avoid repeating this code
125 * function ContextLazyLoad() {}
126 * ContextLazyLoad.prototype.getContext = function () {
127 * if ( !this.context ) {
128 * this.context = new Context();
129 * }
130 * return this.context;
131 * };
132 *
133 * function FooBar() {}
134 * OO.inheritClass( FooBar, Foo );
135 * OO.mixinClass( FooBar, ContextLazyLoad );
136 *
137 * @param {Function} targetFn
138 * @param {Function} originFn
139 */
140 oo.mixinClass = function ( targetFn, originFn ) {
141 var key;
142
143 if ( !originFn ) {
144 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn + ')' );
145 }
146
147 // Copy prototype properties
148 for ( key in originFn.prototype ) {
149 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) {
150 targetFn.prototype[ key ] = originFn.prototype[ key ];
151 }
152 }
153
154 // Copy static properties - always initialize both sides
155 oo.initClass( targetFn );
156 if ( originFn.static ) {
157 for ( key in originFn.static ) {
158 if ( hasOwn.call( originFn.static, key ) ) {
159 targetFn.static[ key ] = originFn.static[ key ];
160 }
161 }
162 } else {
163 oo.initClass( originFn );
164 }
165 };
166
167 /**
168 * Test whether one class is a subclass of another, without instantiating it.
169 *
170 * Every class is considered a subclass of Object and of itself.
171 *
172 * @param {Function} testFn The class to be tested
173 * @param {Function} baseFn The base class
174 * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it)
175 */
176 oo.isSubclass = function ( testFn, baseFn ) {
177 return testFn === baseFn || testFn.prototype instanceof baseFn;
178 };
179
180 /* Object Methods */
181
182 /**
183 * Get a deeply nested property of an object using variadic arguments, protecting against
184 * undefined property errors.
185 *
186 * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
187 * except that the former protects against JS errors if one of the intermediate properties
188 * is undefined. Instead of throwing an error, this function will return undefined in
189 * that case.
190 *
191 * @param {Object} obj
192 * @param {...Mixed} [keys]
193 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
194 */
195 oo.getProp = function ( obj ) {
196 var i,
197 retval = obj;
198 for ( i = 1; i < arguments.length; i++ ) {
199 if ( retval === undefined || retval === null ) {
200 // Trying to access a property of undefined or null causes an error
201 return undefined;
202 }
203 retval = retval[ arguments[ i ] ];
204 }
205 return retval;
206 };
207
208 /**
209 * Set a deeply nested property of an object using variadic arguments, protecting against
210 * undefined property errors.
211 *
212 * `oo.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
213 * the former protects against JS errors if one of the intermediate properties is
214 * undefined. Instead of throwing an error, undefined intermediate properties will be
215 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
216 * is not an object, this function will silently abort.
217 *
218 * @param {Object} obj
219 * @param {...Mixed} [keys]
220 * @param {Mixed} [value]
221 */
222 oo.setProp = function ( obj ) {
223 var i,
224 prop = obj;
225 if ( Object( obj ) !== obj || arguments.length < 2 ) {
226 return;
227 }
228 for ( i = 1; i < arguments.length - 2; i++ ) {
229 if ( prop[ arguments[ i ] ] === undefined ) {
230 prop[ arguments[ i ] ] = {};
231 }
232 if ( Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] ) {
233 return;
234 }
235 prop = prop[ arguments[ i ] ];
236 }
237 prop[ arguments[ arguments.length - 2 ] ] = arguments[ arguments.length - 1 ];
238 };
239
240 /**
241 * Delete a deeply nested property of an object using variadic arguments, protecting against
242 * undefined property errors, and deleting resulting empty objects.
243 *
244 * @param {Object} obj
245 * @param {...Mixed} [keys]
246 */
247 oo.deleteProp = function ( obj ) {
248 var i,
249 prop = obj,
250 props = [ prop ];
251 if ( Object( obj ) !== obj || arguments.length < 2 ) {
252 return;
253 }
254 for ( i = 1; i < arguments.length - 1; i++ ) {
255 if ( prop[ arguments[ i ] ] === undefined || Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] ) {
256 return;
257 }
258 prop = prop[ arguments[ i ] ];
259 props.push( prop );
260 }
261 delete prop[ arguments[ i ] ];
262 // Walk back through props removing any plain empty objects
263 while ( props.length > 1 && ( prop = props.pop() ) && oo.isPlainObject( prop ) && !Object.keys( prop ).length ) {
264 delete props[ props.length - 1 ][ arguments[ props.length ] ];
265 }
266 };
267
268 /**
269 * Create a new object that is an instance of the same
270 * constructor as the input, inherits from the same object
271 * and contains the same own properties.
272 *
273 * This makes a shallow non-recursive copy of own properties.
274 * To create a recursive copy of plain objects, use #copy.
275 *
276 * var foo = new Person( mom, dad );
277 * foo.setAge( 21 );
278 * var foo2 = OO.cloneObject( foo );
279 * foo.setAge( 22 );
280 *
281 * // Then
282 * foo2 !== foo; // true
283 * foo2 instanceof Person; // true
284 * foo2.getAge(); // 21
285 * foo.getAge(); // 22
286 *
287 * @param {Object} origin
288 * @return {Object} Clone of origin
289 */
290 oo.cloneObject = function ( origin ) {
291 var key, r;
292
293 r = Object.create( origin.constructor.prototype );
294
295 for ( key in origin ) {
296 if ( hasOwn.call( origin, key ) ) {
297 r[ key ] = origin[ key ];
298 }
299 }
300
301 return r;
302 };
303
304 /**
305 * Get an array of all property values in an object.
306 *
307 * @param {Object} obj Object to get values from
308 * @return {Array} List of object values
309 */
310 oo.getObjectValues = function ( obj ) {
311 var key, values;
312
313 if ( obj !== Object( obj ) ) {
314 throw new TypeError( 'Called on non-object' );
315 }
316
317 values = [];
318 for ( key in obj ) {
319 if ( hasOwn.call( obj, key ) ) {
320 values[ values.length ] = obj[ key ];
321 }
322 }
323
324 return values;
325 };
326
327 /**
328 * Use binary search to locate an element in a sorted array.
329 *
330 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
331 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
332 * below 0 if it is to the left of elem, or zero if it's equal to elem.
333 *
334 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
335 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
336 * `searchFunc = cmp.bind( null, value )`.
337 *
338 * @param {Array} arr Array to search in
339 * @param {Function} searchFunc Search function
340 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
341 * @return {number|null} Index where val was found, or null if not found
342 */
343 oo.binarySearch = function ( arr, searchFunc, forInsertion ) {
344 var mid, cmpResult,
345 left = 0,
346 right = arr.length;
347 while ( left < right ) {
348 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
349 // eslint-disable-next-line no-bitwise
350 mid = ( left + right ) >> 1;
351 cmpResult = searchFunc( arr[ mid ] );
352 if ( cmpResult < 0 ) {
353 right = mid;
354 } else if ( cmpResult > 0 ) {
355 left = mid + 1;
356 } else {
357 return mid;
358 }
359 }
360 return forInsertion ? right : null;
361 };
362
363 /**
364 * Recursively compare properties between two objects.
365 *
366 * A false result may be caused by property inequality or by properties in one object missing from
367 * the other. An asymmetrical test may also be performed, which checks only that properties in the
368 * first object are present in the second object, but not the inverse.
369 *
370 * If either a or b is null or undefined it will be treated as an empty object.
371 *
372 * @param {Object|undefined|null} a First object to compare
373 * @param {Object|undefined|null} b Second object to compare
374 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
375 * (i.e. a is a subset of b)
376 * @return {boolean} If the objects contain the same values as each other
377 */
378 oo.compare = function ( a, b, asymmetrical ) {
379 var aValue, bValue, aType, bType, k;
380
381 if ( a === b ) {
382 return true;
383 }
384
385 a = a || {};
386 b = b || {};
387
388 if ( typeof a.nodeType === 'number' && typeof a.isEqualNode === 'function' ) {
389 return a.isEqualNode( b );
390 }
391
392 for ( k in a ) {
393 if ( !hasOwn.call( a, k ) || a[ k ] === undefined || a[ k ] === b[ k ] ) {
394 // Ignore undefined values, because there is no conceptual difference between
395 // a key that is absent and a key that is present but whose value is undefined.
396 continue;
397 }
398
399 aValue = a[ k ];
400 bValue = b[ k ];
401 aType = typeof aValue;
402 bType = typeof bValue;
403 if ( aType !== bType ||
404 (
405 ( aType === 'string' || aType === 'number' || aType === 'boolean' ) &&
406 aValue !== bValue
407 ) ||
408 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, true ) ) ) {
409 return false;
410 }
411 }
412 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
413 return asymmetrical ? true : oo.compare( b, a, true );
414 };
415
416 /**
417 * Create a plain deep copy of any kind of object.
418 *
419 * Copies are deep, and will either be an object or an array depending on `source`.
420 *
421 * @param {Object} source Object to copy
422 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
423 * @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.
424 * @return {Object} Copy of source object
425 */
426 oo.copy = function ( source, leafCallback, nodeCallback ) {
427 var key, destination;
428
429 if ( nodeCallback ) {
430 // Extensibility: check before attempting to clone source.
431 destination = nodeCallback( source );
432 if ( destination !== undefined ) {
433 return destination;
434 }
435 }
436
437 if ( Array.isArray( source ) ) {
438 // Array (fall through)
439 destination = new Array( source.length );
440 } else if ( source && typeof source.clone === 'function' ) {
441 // Duck type object with custom clone method
442 return leafCallback ? leafCallback( source.clone() ) : source.clone();
443 } else if ( source && typeof source.cloneNode === 'function' ) {
444 // DOM Node
445 return leafCallback ?
446 leafCallback( source.cloneNode( true ) ) :
447 source.cloneNode( true );
448 } else if ( oo.isPlainObject( source ) ) {
449 // Plain objects (fall through)
450 destination = {};
451 } else {
452 // Non-plain objects (incl. functions) and primitive values
453 return leafCallback ? leafCallback( source ) : source;
454 }
455
456 // source is an array or a plain object
457 for ( key in source ) {
458 destination[ key ] = oo.copy( source[ key ], leafCallback, nodeCallback );
459 }
460
461 // This is an internal node, so we don't apply the leafCallback.
462 return destination;
463 };
464
465 /**
466 * Generate a hash of an object based on its name and data.
467 *
468 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
469 *
470 * To avoid two objects with the same values generating different hashes, we utilize the replacer
471 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
472 * not be the fastest way to do this; we should investigate this further.
473 *
474 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
475 * function, we call that function and use its return value rather than hashing the object
476 * ourselves. This allows classes to define custom hashing.
477 *
478 * @param {Object} val Object to generate hash for
479 * @return {string} Hash of object
480 */
481 oo.getHash = function ( val ) {
482 return JSON.stringify( val, oo.getHash.keySortReplacer );
483 };
484
485 /**
486 * Sort objects by key (helper function for OO.getHash).
487 *
488 * This is a callback passed into JSON.stringify.
489 *
490 * @method getHash_keySortReplacer
491 * @param {string} key Property name of value being replaced
492 * @param {Mixed} val Property value to replace
493 * @return {Mixed} Replacement value
494 */
495 oo.getHash.keySortReplacer = function ( key, val ) {
496 var normalized, keys, i, len;
497 if ( val && typeof val.getHashObject === 'function' ) {
498 // This object has its own custom hash function, use it
499 val = val.getHashObject();
500 }
501 if ( !Array.isArray( val ) && Object( val ) === val ) {
502 // Only normalize objects when the key-order is ambiguous
503 // (e.g. any object not an array).
504 normalized = {};
505 keys = Object.keys( val ).sort();
506 i = 0;
507 len = keys.length;
508 for ( ; i < len; i += 1 ) {
509 normalized[ keys[ i ] ] = val[ keys[ i ] ];
510 }
511 return normalized;
512 } else {
513 // Primitive values and arrays get stable hashes
514 // by default. Lets those be stringified as-is.
515 return val;
516 }
517 };
518
519 /**
520 * Get the unique values of an array, removing duplicates
521 *
522 * @param {Array} arr Array
523 * @return {Array} Unique values in array
524 */
525 oo.unique = function ( arr ) {
526 return arr.reduce( function ( result, current ) {
527 if ( result.indexOf( current ) === -1 ) {
528 result.push( current );
529 }
530 return result;
531 }, [] );
532 };
533
534 /**
535 * Compute the union (duplicate-free merge) of a set of arrays.
536 *
537 * Arrays values must be convertable to object keys (strings).
538 *
539 * By building an object (with the values for keys) in parallel with
540 * the array, a new item's existence in the union can be computed faster.
541 *
542 * @param {...Array} arrays Arrays to union
543 * @return {Array} Union of the arrays
544 */
545 oo.simpleArrayUnion = function () {
546 var i, ilen, arr, j, jlen,
547 obj = {},
548 result = [];
549
550 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) {
551 arr = arguments[ i ];
552 for ( j = 0, jlen = arr.length; j < jlen; j++ ) {
553 if ( !obj[ arr[ j ] ] ) {
554 obj[ arr[ j ] ] = true;
555 result.push( arr[ j ] );
556 }
557 }
558 }
559
560 return result;
561 };
562
563 /**
564 * Combine arrays (intersection or difference).
565 *
566 * An intersection checks the item exists in 'b' while difference checks it doesn't.
567 *
568 * Arrays values must be convertable to object keys (strings).
569 *
570 * By building an object (with the values for keys) of 'b' we can
571 * compute the result faster.
572 *
573 * @private
574 * @param {Array} a First array
575 * @param {Array} b Second array
576 * @param {boolean} includeB Whether to items in 'b'
577 * @return {Array} Combination (intersection or difference) of arrays
578 */
579 function simpleArrayCombine( a, b, includeB ) {
580 var i, ilen, isInB,
581 bObj = {},
582 result = [];
583
584 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
585 bObj[ b[ i ] ] = true;
586 }
587
588 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
589 isInB = !!bObj[ a[ i ] ];
590 if ( isInB === includeB ) {
591 result.push( a[ i ] );
592 }
593 }
594
595 return result;
596 }
597
598 /**
599 * Compute the intersection of two arrays (items in both arrays).
600 *
601 * Arrays values must be convertable to object keys (strings).
602 *
603 * @param {Array} a First array
604 * @param {Array} b Second array
605 * @return {Array} Intersection of arrays
606 */
607 oo.simpleArrayIntersection = function ( a, b ) {
608 return simpleArrayCombine( a, b, true );
609 };
610
611 /**
612 * Compute the difference of two arrays (items in 'a' but not 'b').
613 *
614 * Arrays values must be convertable to object keys (strings).
615 *
616 * @param {Array} a First array
617 * @param {Array} b Second array
618 * @return {Array} Intersection of arrays
619 */
620 oo.simpleArrayDifference = function ( a, b ) {
621 return simpleArrayCombine( a, b, false );
622 };
623
624 /* global $ */
625
626 oo.isPlainObject = $.isPlainObject;
627
628 /* global hasOwn */
629
630 ( function () {
631
632 /**
633 * @class OO.EventEmitter
634 *
635 * @constructor
636 */
637 oo.EventEmitter = function OoEventEmitter() {
638 // Properties
639
640 /**
641 * Storage of bound event handlers by event name.
642 *
643 * @property
644 */
645 this.bindings = {};
646 };
647
648 oo.initClass( oo.EventEmitter );
649
650 /* Private helper functions */
651
652 /**
653 * Validate a function or method call in a context
654 *
655 * For a method name, check that it names a function in the context object
656 *
657 * @private
658 * @param {Function|string} method Function or method name
659 * @param {Mixed} context The context of the call
660 * @throws {Error} A method name is given but there is no context
661 * @throws {Error} In the context object, no property exists with the given name
662 * @throws {Error} In the context object, the named property is not a function
663 */
664 function validateMethod( method, context ) {
665 // Validate method and context
666 if ( typeof method === 'string' ) {
667 // Validate method
668 if ( context === undefined || context === null ) {
669 throw new Error( 'Method name "' + method + '" has no context.' );
670 }
671 if ( typeof context[ method ] !== 'function' ) {
672 // Technically the property could be replaced by a function before
673 // call time. But this probably signals a typo.
674 throw new Error( 'Property "' + method + '" is not a function' );
675 }
676 } else if ( typeof method !== 'function' ) {
677 throw new Error( 'Invalid callback. Function or method name expected.' );
678 }
679 }
680
681 /**
682 * @private
683 * @param {OO.EventEmitter} eventEmitter Event emitter
684 * @param {string} event Event name
685 * @param {Object} binding
686 */
687 function addBinding( eventEmitter, event, binding ) {
688 var bindings;
689 // Auto-initialize bindings list
690 if ( hasOwn.call( eventEmitter.bindings, event ) ) {
691 bindings = eventEmitter.bindings[ event ];
692 } else {
693 bindings = eventEmitter.bindings[ event ] = [];
694 }
695 // Add binding
696 bindings.push( binding );
697 }
698
699 /* Methods */
700
701 /**
702 * Add a listener to events of a specific event.
703 *
704 * The listener can be a function or the string name of a method; if the latter, then the
705 * name lookup happens at the time the listener is called.
706 *
707 * @param {string} event Type of event to listen to
708 * @param {Function|string} method Function or method name to call when event occurs
709 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
710 * @param {Object} [context=null] Context object for function or method call
711 * @chainable
712 * @throws {Error} Listener argument is not a function or a valid method name
713 */
714 oo.EventEmitter.prototype.on = function ( event, method, args, context ) {
715 validateMethod( method, context );
716
717 // Ensure consistent object shape (optimisation)
718 addBinding( this, event, {
719 method: method,
720 args: args,
721 context: ( arguments.length < 4 ) ? null : context,
722 once: false
723 } );
724 return this;
725 };
726
727 /**
728 * Add a one-time listener to a specific event.
729 *
730 * @param {string} event Type of event to listen to
731 * @param {Function} listener Listener to call when event occurs
732 * @chainable
733 */
734 oo.EventEmitter.prototype.once = function ( event, listener ) {
735 validateMethod( listener );
736
737 // Ensure consistent object shape (optimisation)
738 addBinding( this, event, {
739 method: listener,
740 args: undefined,
741 context: null,
742 once: true
743 } );
744 return this;
745 };
746
747 /**
748 * Remove a specific listener from a specific event.
749 *
750 * @param {string} event Type of event to remove listener from
751 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
752 * to "on". Omit to remove all listeners.
753 * @param {Object} [context=null] Context object function or method call
754 * @chainable
755 * @throws {Error} Listener argument is not a function or a valid method name
756 */
757 oo.EventEmitter.prototype.off = function ( event, method, context ) {
758 var i, bindings;
759
760 if ( arguments.length === 1 ) {
761 // Remove all bindings for event
762 delete this.bindings[ event ];
763 return this;
764 }
765
766 validateMethod( method, context );
767
768 if ( !hasOwn.call( this.bindings, event ) || !this.bindings[ event ].length ) {
769 // No matching bindings
770 return this;
771 }
772
773 // Default to null context
774 if ( arguments.length < 3 ) {
775 context = null;
776 }
777
778 // Remove matching handlers
779 bindings = this.bindings[ event ];
780 i = bindings.length;
781 while ( i-- ) {
782 if ( bindings[ i ].method === method && bindings[ i ].context === context ) {
783 bindings.splice( i, 1 );
784 }
785 }
786
787 // Cleanup if now empty
788 if ( bindings.length === 0 ) {
789 delete this.bindings[ event ];
790 }
791 return this;
792 };
793
794 /**
795 * Emit an event.
796 *
797 * @param {string} event Type of event
798 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
799 * @return {boolean} Whether the event was handled by at least one listener
800 */
801 oo.EventEmitter.prototype.emit = function ( event ) {
802 var args = [],
803 i, len, binding, bindings, method;
804
805 if ( hasOwn.call( this.bindings, event ) ) {
806 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
807 bindings = this.bindings[ event ].slice();
808 for ( i = 1, len = arguments.length; i < len; i++ ) {
809 args.push( arguments[ i ] );
810 }
811 for ( i = 0, len = bindings.length; i < len; i++ ) {
812 binding = bindings[ i ];
813 if ( typeof binding.method === 'string' ) {
814 // Lookup method by name (late binding)
815 method = binding.context[ binding.method ];
816 } else {
817 method = binding.method;
818 }
819 if ( binding.once ) {
820 // Must unbind before calling method to avoid
821 // any nested triggers.
822 this.off( event, method );
823 }
824 method.apply(
825 binding.context,
826 binding.args ? binding.args.concat( args ) : args
827 );
828 }
829 return true;
830 }
831 return false;
832 };
833
834 /**
835 * Connect event handlers to an object.
836 *
837 * @param {Object} context Object to call methods on when events occur
838 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
839 * event bindings keyed by event name containing either method names, functions or arrays containing
840 * method name or function followed by a list of arguments to be passed to callback before emitted
841 * arguments.
842 * @chainable
843 */
844 oo.EventEmitter.prototype.connect = function ( context, methods ) {
845 var method, args, event;
846
847 for ( event in methods ) {
848 method = methods[ event ];
849 // Allow providing additional args
850 if ( Array.isArray( method ) ) {
851 args = method.slice( 1 );
852 method = method[ 0 ];
853 } else {
854 args = [];
855 }
856 // Add binding
857 this.on( event, method, args, context );
858 }
859 return this;
860 };
861
862 /**
863 * Disconnect event handlers from an object.
864 *
865 * @param {Object} context Object to disconnect methods from
866 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
867 * event bindings keyed by event name. Values can be either method names, functions or arrays
868 * containing a method name.
869 * NOTE: To allow matching call sites with connect(), array values are allowed to contain the
870 * parameters as well, but only the method name is used to find bindings. Tt is discouraged to
871 * have multiple bindings for the same event to the same listener, but if used (and only the
872 * parameters vary), disconnecting one variation of (event name, event listener, parameters)
873 * will disconnect other variations as well.
874 * @chainable
875 */
876 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
877 var i, event, method, bindings;
878
879 if ( methods ) {
880 // Remove specific connections to the context
881 for ( event in methods ) {
882 method = methods[ event ];
883 if ( Array.isArray( method ) ) {
884 method = method[ 0 ];
885 }
886 this.off( event, method, context );
887 }
888 } else {
889 // Remove all connections to the context
890 for ( event in this.bindings ) {
891 bindings = this.bindings[ event ];
892 i = bindings.length;
893 while ( i-- ) {
894 // bindings[i] may have been removed by the previous step's
895 // this.off so check it still exists
896 if ( bindings[ i ] && bindings[ i ].context === context ) {
897 this.off( event, bindings[ i ].method, context );
898 }
899 }
900 }
901 }
902
903 return this;
904 };
905
906 }() );
907
908 ( function () {
909
910 /**
911 * Contain and manage a list of OO.EventEmitter items.
912 *
913 * Aggregates and manages their events collectively.
914 *
915 * This mixin must be used in a class that also mixes in OO.EventEmitter.
916 *
917 * @abstract
918 * @class OO.EmitterList
919 * @constructor
920 */
921 oo.EmitterList = function OoEmitterList() {
922 this.items = [];
923 this.aggregateItemEvents = {};
924 };
925
926 /* Events */
927
928 /**
929 * Item has been added
930 *
931 * @event add
932 * @param {OO.EventEmitter} item Added item
933 * @param {number} index Index items were added at
934 */
935
936 /**
937 * Item has been moved to a new index
938 *
939 * @event move
940 * @param {OO.EventEmitter} item Moved item
941 * @param {number} index Index item was moved to
942 * @param {number} oldIndex The original index the item was in
943 */
944
945 /**
946 * Item has been removed
947 *
948 * @event remove
949 * @param {OO.EventEmitter} item Removed item
950 * @param {number} index Index the item was removed from
951 */
952
953 /**
954 * @event clear The list has been cleared of items
955 */
956
957 /* Methods */
958
959 /**
960 * Normalize requested index to fit into the bounds of the given array.
961 *
962 * @private
963 * @static
964 * @param {Array} arr Given array
965 * @param {number|undefined} index Requested index
966 * @return {number} Normalized index
967 */
968 function normalizeArrayIndex( arr, index ) {
969 return ( index === undefined || index < 0 || index >= arr.length ) ?
970 arr.length :
971 index;
972 }
973
974 /**
975 * Get all items.
976 *
977 * @return {OO.EventEmitter[]} Items in the list
978 */
979 oo.EmitterList.prototype.getItems = function () {
980 return this.items.slice( 0 );
981 };
982
983 /**
984 * Get the index of a specific item.
985 *
986 * @param {OO.EventEmitter} item Requested item
987 * @return {number} Index of the item
988 */
989 oo.EmitterList.prototype.getItemIndex = function ( item ) {
990 return this.items.indexOf( item );
991 };
992
993 /**
994 * Get number of items.
995 *
996 * @return {number} Number of items in the list
997 */
998 oo.EmitterList.prototype.getItemCount = function () {
999 return this.items.length;
1000 };
1001
1002 /**
1003 * Check if a list contains no items.
1004 *
1005 * @return {boolean} Group is empty
1006 */
1007 oo.EmitterList.prototype.isEmpty = function () {
1008 return !this.items.length;
1009 };
1010
1011 /**
1012 * Aggregate the events emitted by the group.
1013 *
1014 * When events are aggregated, the group will listen to all contained items for the event,
1015 * and then emit the event under a new name. The new event will contain an additional leading
1016 * parameter containing the item that emitted the original event. Other arguments emitted from
1017 * the original event are passed through.
1018 *
1019 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
1020 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
1021 * A `null` value will remove aggregated events.
1022
1023 * @throws {Error} If aggregation already exists
1024 */
1025 oo.EmitterList.prototype.aggregate = function ( events ) {
1026 var i, item, add, remove, itemEvent, groupEvent;
1027
1028 for ( itemEvent in events ) {
1029 groupEvent = events[ itemEvent ];
1030
1031 // Remove existing aggregated event
1032 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
1033 // Don't allow duplicate aggregations
1034 if ( groupEvent ) {
1035 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
1036 }
1037 // Remove event aggregation from existing items
1038 for ( i = 0; i < this.items.length; i++ ) {
1039 item = this.items[ i ];
1040 if ( item.connect && item.disconnect ) {
1041 remove = {};
1042 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
1043 item.disconnect( this, remove );
1044 }
1045 }
1046 // Prevent future items from aggregating event
1047 delete this.aggregateItemEvents[ itemEvent ];
1048 }
1049
1050 // Add new aggregate event
1051 if ( groupEvent ) {
1052 // Make future items aggregate event
1053 this.aggregateItemEvents[ itemEvent ] = groupEvent;
1054 // Add event aggregation to existing items
1055 for ( i = 0; i < this.items.length; i++ ) {
1056 item = this.items[ i ];
1057 if ( item.connect && item.disconnect ) {
1058 add = {};
1059 add[ itemEvent ] = [ 'emit', groupEvent, item ];
1060 item.connect( this, add );
1061 }
1062 }
1063 }
1064 }
1065 };
1066
1067 /**
1068 * Add items to the list.
1069 *
1070 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1071 * an array of items to add
1072 * @param {number} [index] Index to add items at. If no index is
1073 * given, or if the index that is given is invalid, the item
1074 * will be added at the end of the list.
1075 * @chainable
1076 * @fires add
1077 * @fires move
1078 */
1079 oo.EmitterList.prototype.addItems = function ( items, index ) {
1080 var i, oldIndex;
1081
1082 if ( !Array.isArray( items ) ) {
1083 items = [ items ];
1084 }
1085
1086 if ( items.length === 0 ) {
1087 return this;
1088 }
1089
1090 index = normalizeArrayIndex( this.items, index );
1091 for ( i = 0; i < items.length; i++ ) {
1092 oldIndex = this.items.indexOf( items[ i ] );
1093 if ( oldIndex !== -1 ) {
1094 // Move item to new index
1095 index = this.moveItem( items[ i ], index );
1096 this.emit( 'move', items[ i ], index, oldIndex );
1097 } else {
1098 // insert item at index
1099 index = this.insertItem( items[ i ], index );
1100 this.emit( 'add', items[ i ], index );
1101 }
1102 index++;
1103 }
1104
1105 return this;
1106 };
1107
1108 /**
1109 * Move an item from its current position to a new index.
1110 *
1111 * The item is expected to exist in the list. If it doesn't,
1112 * the method will throw an exception.
1113 *
1114 * @private
1115 * @param {OO.EventEmitter} item Items to add
1116 * @param {number} newIndex Index to move the item to
1117 * @return {number} The index the item was moved to
1118 * @throws {Error} If item is not in the list
1119 */
1120 oo.EmitterList.prototype.moveItem = function ( item, newIndex ) {
1121 var existingIndex = this.items.indexOf( item );
1122
1123 if ( existingIndex === -1 ) {
1124 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1125 }
1126
1127 newIndex = normalizeArrayIndex( this.items, newIndex );
1128
1129 // Remove the item from the current index
1130 this.items.splice( existingIndex, 1 );
1131
1132 // If necessary, adjust new index after removal
1133 if ( existingIndex < newIndex ) {
1134 newIndex--;
1135 }
1136
1137 // Move the item to the new index
1138 this.items.splice( newIndex, 0, item );
1139
1140 return newIndex;
1141 };
1142
1143 /**
1144 * Utility method to insert an item into the list, and
1145 * connect it to aggregate events.
1146 *
1147 * Don't call this directly unless you know what you're doing.
1148 * Use #addItems instead.
1149 *
1150 * This method can be extended in child classes to produce
1151 * different behavior when an item is inserted. For example,
1152 * inserted items may also be attached to the DOM or may
1153 * interact with some other nodes in certain ways. Extending
1154 * this method is allowed, but if overriden, the aggregation
1155 * of events must be preserved, or behavior of emitted events
1156 * will be broken.
1157 *
1158 * If you are extending this method, please make sure the
1159 * parent method is called.
1160 *
1161 * @protected
1162 * @param {OO.EventEmitter} item Items to add
1163 * @param {number} index Index to add items at
1164 * @return {number} The index the item was added at
1165 */
1166 oo.EmitterList.prototype.insertItem = function ( item, index ) {
1167 var events, event;
1168
1169 // Add the item to event aggregation
1170 if ( item.connect && item.disconnect ) {
1171 events = {};
1172 for ( event in this.aggregateItemEvents ) {
1173 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
1174 }
1175 item.connect( this, events );
1176 }
1177
1178 index = normalizeArrayIndex( this.items, index );
1179
1180 // Insert into items array
1181 this.items.splice( index, 0, item );
1182 return index;
1183 };
1184
1185 /**
1186 * Remove items.
1187 *
1188 * @param {OO.EventEmitter[]} items Items to remove
1189 * @chainable
1190 * @fires remove
1191 */
1192 oo.EmitterList.prototype.removeItems = function ( items ) {
1193 var i, item, index;
1194
1195 if ( !Array.isArray( items ) ) {
1196 items = [ items ];
1197 }
1198
1199 if ( items.length === 0 ) {
1200 return this;
1201 }
1202
1203 // Remove specific items
1204 for ( i = 0; i < items.length; i++ ) {
1205 item = items[ i ];
1206 index = this.items.indexOf( item );
1207 if ( index !== -1 ) {
1208 if ( item.connect && item.disconnect ) {
1209 // Disconnect all listeners from the item
1210 item.disconnect( this );
1211 }
1212 this.items.splice( index, 1 );
1213 this.emit( 'remove', item, index );
1214 }
1215 }
1216
1217 return this;
1218 };
1219
1220 /**
1221 * Clear all items
1222 *
1223 * @chainable
1224 * @fires clear
1225 */
1226 oo.EmitterList.prototype.clearItems = function () {
1227 var i, item,
1228 cleared = this.items.splice( 0, this.items.length );
1229
1230 // Disconnect all items
1231 for ( i = 0; i < cleared.length; i++ ) {
1232 item = cleared[ i ];
1233 if ( item.connect && item.disconnect ) {
1234 item.disconnect( this );
1235 }
1236 }
1237
1238 this.emit( 'clear' );
1239
1240 return this;
1241 };
1242
1243 }() );
1244
1245 /**
1246 * Manage a sorted list of OO.EmitterList objects.
1247 *
1248 * The sort order is based on a callback that compares two items. The return value of
1249 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1250 * if a is equal to b. The callback should only return zero if the two objects are
1251 * considered equal.
1252 *
1253 * When an item changes in a way that could affect their sorting behavior, it must
1254 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1255 *
1256 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1257 *
1258 * @abstract
1259 * @class OO.SortedEmitterList
1260 * @mixins OO.EmitterList
1261 * @constructor
1262 * @param {Function} sortingCallback Callback that compares two items.
1263 */
1264 oo.SortedEmitterList = function OoSortedEmitterList( sortingCallback ) {
1265 // Mixin constructors
1266 oo.EmitterList.call( this );
1267
1268 this.sortingCallback = sortingCallback;
1269
1270 // Listen to sortChange event and make sure
1271 // we re-sort the changed item when that happens
1272 this.aggregate( {
1273 sortChange: 'itemSortChange'
1274 } );
1275
1276 this.connect( this, {
1277 itemSortChange: 'onItemSortChange'
1278 } );
1279 };
1280
1281 oo.mixinClass( oo.SortedEmitterList, oo.EmitterList );
1282
1283 /* Events */
1284
1285 /**
1286 * An item has changed properties that affect its sort positioning
1287 * inside the list.
1288 *
1289 * @private
1290 * @event itemSortChange
1291 */
1292
1293 /* Methods */
1294
1295 /**
1296 * Handle a case where an item changed a property that relates
1297 * to its sorted order
1298 *
1299 * @param {OO.EventEmitter} item Item in the list
1300 */
1301 oo.SortedEmitterList.prototype.onItemSortChange = function ( item ) {
1302 // Remove the item
1303 this.removeItems( item );
1304 // Re-add the item so it is in the correct place
1305 this.addItems( item );
1306 };
1307
1308 /**
1309 * Change the sorting callback for this sorted list.
1310 *
1311 * The callback receives two items. The return value of callback(a, b) must be less than zero
1312 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1313 *
1314 * @param {Function} sortingCallback Sorting callback
1315 */
1316 oo.SortedEmitterList.prototype.setSortingCallback = function ( sortingCallback ) {
1317 var items = this.getItems();
1318
1319 this.sortingCallback = sortingCallback;
1320
1321 // Empty the list
1322 this.clearItems();
1323 // Re-add the items in the new order
1324 this.addItems( items );
1325 };
1326
1327 /**
1328 * Add items to the sorted list.
1329 *
1330 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1331 * an array of items to add
1332 * @chainable
1333 */
1334 oo.SortedEmitterList.prototype.addItems = function ( items ) {
1335 var index, i, insertionIndex;
1336
1337 if ( !Array.isArray( items ) ) {
1338 items = [ items ];
1339 }
1340
1341 if ( items.length === 0 ) {
1342 return this;
1343 }
1344
1345 for ( i = 0; i < items.length; i++ ) {
1346 // Find insertion index
1347 insertionIndex = this.findInsertionIndex( items[ i ] );
1348
1349 // Check if the item exists using the sorting callback
1350 // and remove it first if it exists
1351 if (
1352 // First make sure the insertion index is not at the end
1353 // of the list (which means it does not point to any actual
1354 // items)
1355 insertionIndex <= this.items.length &&
1356 // Make sure there actually is an item in this index
1357 this.items[ insertionIndex ] &&
1358 // The callback returns 0 if the items are equal
1359 this.sortingCallback( this.items[ insertionIndex ], items[ i ] ) === 0
1360 ) {
1361 // Remove the existing item
1362 this.removeItems( this.items[ insertionIndex ] );
1363 }
1364
1365 // Insert item at the insertion index
1366 index = this.insertItem( items[ i ], insertionIndex );
1367 this.emit( 'add', items[ i ], index );
1368 }
1369
1370 return this;
1371 };
1372
1373 /**
1374 * Find the index a given item should be inserted at. If the item is already
1375 * in the list, this will return the index where the item currently is.
1376 *
1377 * @param {OO.EventEmitter} item Items to insert
1378 * @return {number} The index the item should be inserted at
1379 */
1380 oo.SortedEmitterList.prototype.findInsertionIndex = function ( item ) {
1381 var list = this;
1382
1383 return oo.binarySearch(
1384 this.items,
1385 // Fake a this.sortingCallback.bind( null, item ) call here
1386 // otherwise this doesn't pass tests in phantomJS
1387 function ( otherItem ) {
1388 return list.sortingCallback( item, otherItem );
1389 },
1390 true
1391 );
1392
1393 };
1394
1395 /* global hasOwn */
1396
1397 /**
1398 * A map interface for associating arbitrary data with a symbolic name. Used in
1399 * place of a plain object to provide additional {@link #method-register registration}
1400 * or {@link #method-lookup lookup} functionality.
1401 *
1402 * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>.
1403 *
1404 * @class OO.Registry
1405 * @mixins OO.EventEmitter
1406 *
1407 * @constructor
1408 */
1409 oo.Registry = function OoRegistry() {
1410 // Mixin constructors
1411 oo.EventEmitter.call( this );
1412
1413 // Properties
1414 this.registry = {};
1415 };
1416
1417 /* Inheritance */
1418
1419 oo.mixinClass( oo.Registry, oo.EventEmitter );
1420
1421 /* Events */
1422
1423 /**
1424 * @event register
1425 * @param {string} name
1426 * @param {Mixed} data
1427 */
1428
1429 /**
1430 * @event unregister
1431 * @param {string} name
1432 * @param {Mixed} data Data removed from registry
1433 */
1434
1435 /* Methods */
1436
1437 /**
1438 * Associate one or more symbolic names with some data.
1439 *
1440 * Any existing entry with the same name will be overridden.
1441 *
1442 * @param {string|string[]} name Symbolic name or list of symbolic names
1443 * @param {Mixed} data Data to associate with symbolic name
1444 * @fires register
1445 * @throws {Error} Name argument must be a string or array
1446 */
1447 oo.Registry.prototype.register = function ( name, data ) {
1448 var i, len;
1449 if ( typeof name === 'string' ) {
1450 this.registry[ name ] = data;
1451 this.emit( 'register', name, data );
1452 } else if ( Array.isArray( name ) ) {
1453 for ( i = 0, len = name.length; i < len; i++ ) {
1454 this.register( name[ i ], data );
1455 }
1456 } else {
1457 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1458 }
1459 };
1460
1461 /**
1462 * Remove one or more symbolic names from the registry
1463 *
1464 * @param {string|string[]} name Symbolic name or list of symbolic names
1465 * @fires unregister
1466 * @throws {Error} Name argument must be a string or array
1467 */
1468 oo.Registry.prototype.unregister = function ( name ) {
1469 var i, len, data;
1470 if ( typeof name === 'string' ) {
1471 data = this.lookup( name );
1472 if ( data !== undefined ) {
1473 delete this.registry[ name ];
1474 this.emit( 'unregister', name, data );
1475 }
1476 } else if ( Array.isArray( name ) ) {
1477 for ( i = 0, len = name.length; i < len; i++ ) {
1478 this.unregister( name[ i ] );
1479 }
1480 } else {
1481 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1482 }
1483 };
1484
1485 /**
1486 * Get data for a given symbolic name.
1487 *
1488 * @param {string} name Symbolic name
1489 * @return {Mixed|undefined} Data associated with symbolic name
1490 */
1491 oo.Registry.prototype.lookup = function ( name ) {
1492 if ( hasOwn.call( this.registry, name ) ) {
1493 return this.registry[ name ];
1494 }
1495 };
1496
1497 /**
1498 * @class OO.Factory
1499 * @extends OO.Registry
1500 *
1501 * @constructor
1502 */
1503 oo.Factory = function OoFactory() {
1504 // Parent constructor
1505 oo.Factory.super.call( this );
1506 };
1507
1508 /* Inheritance */
1509
1510 oo.inheritClass( oo.Factory, oo.Registry );
1511
1512 /* Methods */
1513
1514 /**
1515 * Register a constructor with the factory.
1516 *
1517 * Classes must have a static `name` property to be registered.
1518 *
1519 * function MyClass() {};
1520 * OO.initClass( MyClass );
1521 * // Adds a static property to the class defining a symbolic name
1522 * MyClass.static.name = 'mine';
1523 * // Registers class with factory, available via symbolic name 'mine'
1524 * factory.register( MyClass );
1525 *
1526 * @param {Function} constructor Constructor to use when creating object
1527 * @throws {Error} Name must be a string and must not be empty
1528 * @throws {Error} Constructor must be a function
1529 */
1530 oo.Factory.prototype.register = function ( constructor ) {
1531 var name;
1532
1533 if ( typeof constructor !== 'function' ) {
1534 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1535 }
1536 name = constructor.static && constructor.static.name;
1537 if ( typeof name !== 'string' || name === '' ) {
1538 throw new Error( 'Name must be a string and must not be empty' );
1539 }
1540
1541 // Parent method
1542 oo.Factory.super.prototype.register.call( this, name, constructor );
1543 };
1544
1545 /**
1546 * Unregister a constructor from the factory.
1547 *
1548 * @param {Function} constructor Constructor to unregister
1549 * @throws {Error} Name must be a string and must not be empty
1550 * @throws {Error} Constructor must be a function
1551 */
1552 oo.Factory.prototype.unregister = function ( constructor ) {
1553 var name;
1554
1555 if ( typeof constructor !== 'function' ) {
1556 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1557 }
1558 name = constructor.static && constructor.static.name;
1559 if ( typeof name !== 'string' || name === '' ) {
1560 throw new Error( 'Name must be a string and must not be empty' );
1561 }
1562
1563 // Parent method
1564 oo.Factory.super.prototype.unregister.call( this, name );
1565 };
1566
1567 /**
1568 * Create an object based on a name.
1569 *
1570 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1571 * constructor directly, so leaving one out will pass an undefined to the constructor.
1572 *
1573 * @param {string} name Object name
1574 * @param {...Mixed} [args] Arguments to pass to the constructor
1575 * @return {Object} The new object
1576 * @throws {Error} Unknown object name
1577 */
1578 oo.Factory.prototype.create = function ( name ) {
1579 var obj, i,
1580 args = [],
1581 constructor = this.lookup( name );
1582
1583 if ( !constructor ) {
1584 throw new Error( 'No class registered by that name: ' + name );
1585 }
1586
1587 // Convert arguments to array and shift the first argument (name) off
1588 for ( i = 1; i < arguments.length; i++ ) {
1589 args.push( arguments[ i ] );
1590 }
1591
1592 // We can't use the "new" operator with .apply directly because apply needs a
1593 // context. So instead just do what "new" does: create an object that inherits from
1594 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1595 // then invoke the constructor with the object as context, and return it (ignoring
1596 // the constructor's return value).
1597 obj = Object.create( constructor.prototype );
1598 constructor.apply( obj, args );
1599 return obj;
1600 };
1601
1602 /* eslint-env node */
1603
1604 /* istanbul ignore next */
1605 if ( typeof module !== 'undefined' && module.exports ) {
1606 module.exports = oo;
1607 } else {
1608 global.OO = oo;
1609 }
1610
1611 }( this ) );