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