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