Merge "Show the revision list immediately on "umerge" log action links"
[lhc/web/wiklou.git] / resources / lib / oojs / oojs.jquery.js
1 /*!
2 * OOjs v1.1.0 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
4 *
5 * Copyright 2011-2014 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2014-08-31T21:15:46Z
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 hasOwn = oo.hasOwnProperty,
24 toString = oo.toString;
25
26 /* Class Methods */
27
28 /**
29 * Utility to initialize a class for OO inheritance.
30 *
31 * Currently this just initializes an empty static object.
32 *
33 * @param {Function} fn
34 */
35 oo.initClass = function ( fn ) {
36 fn.static = fn.static || {};
37 };
38
39 /**
40 * Inherit from prototype to another using Object#create.
41 *
42 * Beware: This redefines the prototype, call before setting your prototypes.
43 *
44 * Beware: This redefines the prototype, can only be called once on a function.
45 * If called multiple times on the same function, the previous prototype is lost.
46 * This is how prototypal inheritance works, it can only be one straight chain
47 * (just like classical inheritance in PHP for example). If you need to work with
48 * multiple constructors consider storing an instance of the other constructor in a
49 * property instead, or perhaps use a mixin (see OO.mixinClass).
50 *
51 * function Thing() {}
52 * Thing.prototype.exists = function () {};
53 *
54 * function Person() {
55 * Person.super.apply( this, arguments );
56 * }
57 * OO.inheritClass( Person, Thing );
58 * Person.static.defaultEyeCount = 2;
59 * Person.prototype.walk = function () {};
60 *
61 * function Jumper() {
62 * Jumper.super.apply( this, arguments );
63 * }
64 * OO.inheritClass( Jumper, Person );
65 * Jumper.prototype.jump = function () {};
66 *
67 * Jumper.static.defaultEyeCount === 2;
68 * var x = new Jumper();
69 * x.jump();
70 * x.walk();
71 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
72 *
73 * @param {Function} targetFn
74 * @param {Function} originFn
75 * @throws {Error} If target already inherits from origin
76 */
77 oo.inheritClass = function ( targetFn, originFn ) {
78 if ( targetFn.prototype instanceof originFn ) {
79 throw new Error( 'Target already inherits from origin' );
80 }
81
82 var targetConstructor = targetFn.prototype.constructor;
83
84 // Using ['super'] instead of .super because 'super' is not supported
85 // by IE 8 and below (bug 63303).
86 // Provide .parent as alias for code supporting older browsers which
87 // allows people to comply with their style guide.
88 targetFn['super'] = targetFn.parent = originFn;
89
90 targetFn.prototype = Object.create( originFn.prototype, {
91 // Restore constructor property of targetFn
92 constructor: {
93 value: targetConstructor,
94 enumerable: false,
95 writable: true,
96 configurable: true
97 }
98 } );
99
100 // Extend static properties - always initialize both sides
101 oo.initClass( originFn );
102 targetFn.static = Object.create( originFn.static );
103 };
104
105 /**
106 * Copy over *own* prototype properties of a mixin.
107 *
108 * The 'constructor' (whether implicit or explicit) is not copied over.
109 *
110 * This does not create inheritance to the origin. If inheritance is needed
111 * use oo.inheritClass instead.
112 *
113 * Beware: This can redefine a prototype property, call before setting your prototypes.
114 *
115 * Beware: Don't call before oo.inheritClass.
116 *
117 * function Foo() {}
118 * function Context() {}
119 *
120 * // Avoid repeating this code
121 * function ContextLazyLoad() {}
122 * ContextLazyLoad.prototype.getContext = function () {
123 * if ( !this.context ) {
124 * this.context = new Context();
125 * }
126 * return this.context;
127 * };
128 *
129 * function FooBar() {}
130 * OO.inheritClass( FooBar, Foo );
131 * OO.mixinClass( FooBar, ContextLazyLoad );
132 *
133 * @param {Function} targetFn
134 * @param {Function} originFn
135 */
136 oo.mixinClass = function ( targetFn, originFn ) {
137 var key;
138
139 // Copy prototype properties
140 for ( key in originFn.prototype ) {
141 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) {
142 targetFn.prototype[key] = originFn.prototype[key];
143 }
144 }
145
146 // Copy static properties - always initialize both sides
147 oo.initClass( targetFn );
148 if ( originFn.static ) {
149 for ( key in originFn.static ) {
150 if ( hasOwn.call( originFn.static, key ) ) {
151 targetFn.static[key] = originFn.static[key];
152 }
153 }
154 } else {
155 oo.initClass( originFn );
156 }
157 };
158
159 /* Object Methods */
160
161 /**
162 * Create a new object that is an instance of the same
163 * constructor as the input, inherits from the same object
164 * and contains the same own properties.
165 *
166 * This makes a shallow non-recursive copy of own properties.
167 * To create a recursive copy of plain objects, use #copy.
168 *
169 * var foo = new Person( mom, dad );
170 * foo.setAge( 21 );
171 * var foo2 = OO.cloneObject( foo );
172 * foo.setAge( 22 );
173 *
174 * // Then
175 * foo2 !== foo; // true
176 * foo2 instanceof Person; // true
177 * foo2.getAge(); // 21
178 * foo.getAge(); // 22
179 *
180 * @param {Object} origin
181 * @return {Object} Clone of origin
182 */
183 oo.cloneObject = function ( origin ) {
184 var key, r;
185
186 r = Object.create( origin.constructor.prototype );
187
188 for ( key in origin ) {
189 if ( hasOwn.call( origin, key ) ) {
190 r[key] = origin[key];
191 }
192 }
193
194 return r;
195 };
196
197 /**
198 * Get an array of all property values in an object.
199 *
200 * @param {Object} Object to get values from
201 * @return {Array} List of object values
202 */
203 oo.getObjectValues = function ( obj ) {
204 var key, values;
205
206 if ( obj !== Object( obj ) ) {
207 throw new TypeError( 'Called on non-object' );
208 }
209
210 values = [];
211 for ( key in obj ) {
212 if ( hasOwn.call( obj, key ) ) {
213 values[values.length] = obj[key];
214 }
215 }
216
217 return values;
218 };
219
220 /**
221 * Recursively compare properties between two objects.
222 *
223 * A false result may be caused by property inequality or by properties in one object missing from
224 * the other. An asymmetrical test may also be performed, which checks only that properties in the
225 * first object are present in the second object, but not the inverse.
226 *
227 * If either a or b is null or undefined it will be treated as an empty object.
228 *
229 * @param {Object|undefined|null} a First object to compare
230 * @param {Object|undefined|null} b Second object to compare
231 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
232 * @return {boolean} If the objects contain the same values as each other
233 */
234 oo.compare = function ( a, b, asymmetrical ) {
235 var aValue, bValue, aType, bType, k;
236
237 if ( a === b ) {
238 return true;
239 }
240
241 a = a || {};
242 b = b || {};
243
244 for ( k in a ) {
245 if ( !hasOwn.call( a, k ) ) {
246 // Support es3-shim: Without this filter, comparing [] to {} will be false in ES3
247 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
248 continue;
249 }
250
251 aValue = a[k];
252 bValue = b[k];
253 aType = typeof aValue;
254 bType = typeof bValue;
255 if ( aType !== bType ||
256 ( ( aType === 'string' || aType === 'number' ) && aValue !== bValue ) ||
257 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, asymmetrical ) ) ) {
258 return false;
259 }
260 }
261 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
262 return asymmetrical ? true : oo.compare( b, a, true );
263 };
264
265 /**
266 * Create a plain deep copy of any kind of object.
267 *
268 * Copies are deep, and will either be an object or an array depending on `source`.
269 *
270 * @param {Object} source Object to copy
271 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
272 * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the nodeCallback returns a value other than undefined, the returned value is used instead of attempting to clone.
273 * @return {Object} Copy of source object
274 */
275 oo.copy = function ( source, leafCallback, nodeCallback ) {
276 var key, destination;
277
278 if ( nodeCallback ) {
279 // Extensibility: check before attempting to clone source.
280 destination = nodeCallback( source );
281 if ( destination !== undefined ) {
282 return destination;
283 }
284 }
285
286 if ( Array.isArray( source ) ) {
287 // Array (fall through)
288 destination = new Array( source.length );
289 } else if ( source && typeof source.clone === 'function' ) {
290 // Duck type object with custom clone method
291 return leafCallback ? leafCallback( source.clone() ) : source.clone();
292 } else if ( source && typeof source.cloneNode === 'function' ) {
293 // DOM Node
294 return leafCallback ?
295 leafCallback( source.cloneNode( true ) ) :
296 source.cloneNode( true );
297 } else if ( oo.isPlainObject( source ) ) {
298 // Plain objects (fall through)
299 destination = {};
300 } else {
301 // Non-plain objects (incl. functions) and primitive values
302 return leafCallback ? leafCallback( source ) : source;
303 }
304
305 // source is an array or a plain object
306 for ( key in source ) {
307 destination[key] = oo.copy( source[key], leafCallback, nodeCallback );
308 }
309
310 // This is an internal node, so we don't apply the leafCallback.
311 return destination;
312 };
313
314 /**
315 * Generate a hash of an object based on its name and data.
316 *
317 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
318 *
319 * To avoid two objects with the same values generating different hashes, we utilize the replacer
320 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
321 * not be the fastest way to do this; we should investigate this further.
322 *
323 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
324 * function, we call that function and use its return value rather than hashing the object
325 * ourselves. This allows classes to define custom hashing.
326 *
327 * @param {Object} val Object to generate hash for
328 * @return {string} Hash of object
329 */
330 oo.getHash = function ( val ) {
331 return JSON.stringify( val, oo.getHash.keySortReplacer );
332 };
333
334 /**
335 * Sort objects by key (helper function for OO.getHash).
336 *
337 * This is a callback passed into JSON.stringify.
338 *
339 * @method getHash_keySortReplacer
340 * @param {string} key Property name of value being replaced
341 * @param {Mixed} val Property value to replace
342 * @return {Mixed} Replacement value
343 */
344 oo.getHash.keySortReplacer = function ( key, val ) {
345 var normalized, keys, i, len;
346 if ( val && typeof val.getHashObject === 'function' ) {
347 // This object has its own custom hash function, use it
348 val = val.getHashObject();
349 }
350 if ( !Array.isArray( val ) && Object( val ) === val ) {
351 // Only normalize objects when the key-order is ambiguous
352 // (e.g. any object not an array).
353 normalized = {};
354 keys = Object.keys( val ).sort();
355 i = 0;
356 len = keys.length;
357 for ( ; i < len; i += 1 ) {
358 normalized[keys[i]] = val[keys[i]];
359 }
360 return normalized;
361
362 // Primitive values and arrays get stable hashes
363 // by default. Lets those be stringified as-is.
364 } else {
365 return val;
366 }
367 };
368
369 /**
370 * Compute the union (duplicate-free merge) of a set of arrays.
371 *
372 * Arrays values must be convertable to object keys (strings).
373 *
374 * By building an object (with the values for keys) in parallel with
375 * the array, a new item's existence in the union can be computed faster.
376 *
377 * @param {Array...} arrays Arrays to union
378 * @return {Array} Union of the arrays
379 */
380 oo.simpleArrayUnion = function () {
381 var i, ilen, arr, j, jlen,
382 obj = {},
383 result = [];
384
385 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) {
386 arr = arguments[i];
387 for ( j = 0, jlen = arr.length; j < jlen; j++ ) {
388 if ( !obj[ arr[j] ] ) {
389 obj[ arr[j] ] = true;
390 result.push( arr[j] );
391 }
392 }
393 }
394
395 return result;
396 };
397
398 /**
399 * Combine arrays (intersection or difference).
400 *
401 * An intersection checks the item exists in 'b' while difference checks it doesn't.
402 *
403 * Arrays values must be convertable to object keys (strings).
404 *
405 * By building an object (with the values for keys) of 'b' we can
406 * compute the result faster.
407 *
408 * @private
409 * @param {Array} a First array
410 * @param {Array} b Second array
411 * @param {boolean} includeB Whether to items in 'b'
412 * @return {Array} Combination (intersection or difference) of arrays
413 */
414 function simpleArrayCombine( a, b, includeB ) {
415 var i, ilen, isInB,
416 bObj = {},
417 result = [];
418
419 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
420 bObj[ b[i] ] = true;
421 }
422
423 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
424 isInB = !!bObj[ a[i] ];
425 if ( isInB === includeB ) {
426 result.push( a[i] );
427 }
428 }
429
430 return result;
431 }
432
433 /**
434 * Compute the intersection of two arrays (items in both arrays).
435 *
436 * Arrays values must be convertable to object keys (strings).
437 *
438 * @param {Array} a First array
439 * @param {Array} b Second array
440 * @return {Array} Intersection of arrays
441 */
442 oo.simpleArrayIntersection = function ( a, b ) {
443 return simpleArrayCombine( a, b, true );
444 };
445
446 /**
447 * Compute the difference of two arrays (items in 'a' but not 'b').
448 *
449 * Arrays values must be convertable to object keys (strings).
450 *
451 * @param {Array} a First array
452 * @param {Array} b Second array
453 * @return {Array} Intersection of arrays
454 */
455 oo.simpleArrayDifference = function ( a, b ) {
456 return simpleArrayCombine( a, b, false );
457 };
458
459 /*global $ */
460
461 oo.isPlainObject = $.isPlainObject;
462
463 /*global hasOwn */
464
465 ( function () {
466
467 /**
468 * @class OO.EventEmitter
469 *
470 * @constructor
471 */
472 oo.EventEmitter = function OoEventEmitter() {
473 // Properties
474
475 /**
476 * Storage of bound event handlers by event name.
477 *
478 * @property
479 */
480 this.bindings = {};
481 };
482
483 oo.initClass( oo.EventEmitter );
484
485 /* Private helper functions */
486
487 /**
488 * Validate a function or method call in a context
489 *
490 * For a method name, check that it names a function in the context object
491 *
492 * @private
493 * @param {Function|string} method Function or method name
494 * @param {Mixed} context The context of the call
495 * @throws {Error} A method name is given but there is no context
496 * @throws {Error} In the context object, no property exists with the given name
497 * @throws {Error} In the context object, the named property is not a function
498 */
499 function validateMethod( method, context ) {
500 // Validate method and context
501 if ( typeof method === 'string' ) {
502 // Validate method
503 if ( context === undefined || context === null ) {
504 throw new Error( 'Method name "' + method + '" has no context.' );
505 }
506 if ( !( method in context ) ) {
507 // Technically the method does not need to exist yet: it could be
508 // added before call time. But this probably signals a typo.
509 throw new Error( 'Method not found: "' + method + '"' );
510 }
511 if ( typeof context[method] !== 'function' ) {
512 // Technically the property could be replaced by a function before
513 // call time. But this probably signals a typo.
514 throw new Error( 'Property "' + method + '" is not a function' );
515 }
516 } else if ( typeof method !== 'function' ) {
517 throw new Error( 'Invalid callback. Function or method name expected.' );
518 }
519 }
520
521 /* Methods */
522
523 /**
524 * Add a listener to events of a specific event.
525 *
526 * The listener can be a function or the string name of a method; if the latter, then the
527 * name lookup happens at the time the listener is called.
528 *
529 * @param {string} event Type of event to listen to
530 * @param {Function|string} method Function or method name to call when event occurs
531 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
532 * @param {Object} [context=null] Context object for function or method call
533 * @throws {Error} Listener argument is not a function or a valid method name
534 * @chainable
535 */
536 oo.EventEmitter.prototype.on = function ( event, method, args, context ) {
537 var bindings;
538
539 validateMethod( method, context );
540
541 if ( hasOwn.call( this.bindings, event ) ) {
542 bindings = this.bindings[event];
543 } else {
544 // Auto-initialize bindings list
545 bindings = this.bindings[event] = [];
546 }
547 // Add binding
548 bindings.push( {
549 method: method,
550 args: args,
551 context: ( arguments.length < 4 ) ? null : context
552 } );
553 return this;
554 };
555
556 /**
557 * Add a one-time listener to a specific event.
558 *
559 * @param {string} event Type of event to listen to
560 * @param {Function} listener Listener to call when event occurs
561 * @chainable
562 */
563 oo.EventEmitter.prototype.once = function ( event, listener ) {
564 var eventEmitter = this,
565 listenerWrapper = function () {
566 eventEmitter.off( event, listenerWrapper );
567 listener.apply( eventEmitter, Array.prototype.slice.call( arguments, 0 ) );
568 };
569 return this.on( event, listenerWrapper );
570 };
571
572 /**
573 * Remove a specific listener from a specific event.
574 *
575 * @param {string} event Type of event to remove listener from
576 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
577 * to "on". Omit to remove all listeners.
578 * @param {Object} [context=null] Context object function or method call
579 * @chainable
580 * @throws {Error} Listener argument is not a function or a valid method name
581 */
582 oo.EventEmitter.prototype.off = function ( event, method, context ) {
583 var i, bindings;
584
585 if ( arguments.length === 1 ) {
586 // Remove all bindings for event
587 delete this.bindings[event];
588 return this;
589 }
590
591 validateMethod( method, context );
592
593 if ( !( event in this.bindings ) || !this.bindings[event].length ) {
594 // No matching bindings
595 return this;
596 }
597
598 // Default to null context
599 if ( arguments.length < 3 ) {
600 context = null;
601 }
602
603 // Remove matching handlers
604 bindings = this.bindings[event];
605 i = bindings.length;
606 while ( i-- ) {
607 if ( bindings[i].method === method && bindings[i].context === context ) {
608 bindings.splice( i, 1 );
609 }
610 }
611
612 // Cleanup if now empty
613 if ( bindings.length === 0 ) {
614 delete this.bindings[event];
615 }
616 return this;
617 };
618
619 /**
620 * Emit an event.
621 *
622 * TODO: Should this be chainable? What is the usefulness of the boolean
623 * return value here?
624 *
625 * @param {string} event Type of event
626 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
627 * @return {boolean} If event was handled by at least one listener
628 */
629 oo.EventEmitter.prototype.emit = function ( event ) {
630 var i, len, binding, bindings, args, method;
631
632 if ( event in this.bindings ) {
633 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
634 bindings = this.bindings[event].slice();
635 args = Array.prototype.slice.call( arguments, 1 );
636 for ( i = 0, len = bindings.length; i < len; i++ ) {
637 binding = bindings[i];
638 if ( typeof binding.method === 'string' ) {
639 // Lookup method by name (late binding)
640 method = binding.context[ binding.method ];
641 } else {
642 method = binding.method;
643 }
644 method.apply(
645 binding.context,
646 binding.args ? binding.args.concat( args ) : args
647 );
648 }
649 return true;
650 }
651 return false;
652 };
653
654 /**
655 * Connect event handlers to an object.
656 *
657 * @param {Object} context Object to call methods on when events occur
658 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
659 * event bindings keyed by event name containing either method names, functions or arrays containing
660 * method name or function followed by a list of arguments to be passed to callback before emitted
661 * arguments
662 * @chainable
663 */
664 oo.EventEmitter.prototype.connect = function ( context, methods ) {
665 var method, args, event;
666
667 for ( event in methods ) {
668 method = methods[event];
669 // Allow providing additional args
670 if ( Array.isArray( method ) ) {
671 args = method.slice( 1 );
672 method = method[0];
673 } else {
674 args = [];
675 }
676 // Add binding
677 this.on( event, method, args, context );
678 }
679 return this;
680 };
681
682 /**
683 * Disconnect event handlers from an object.
684 *
685 * @param {Object} context Object to disconnect methods from
686 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
687 * event bindings keyed by event name. Values can be either method names or functions, but must be
688 * consistent with those used in the corresponding call to "connect".
689 * @chainable
690 */
691 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
692 var i, event, bindings;
693
694 if ( methods ) {
695 // Remove specific connections to the context
696 for ( event in methods ) {
697 this.off( event, methods[event], context );
698 }
699 } else {
700 // Remove all connections to the context
701 for ( event in this.bindings ) {
702 bindings = this.bindings[event];
703 i = bindings.length;
704 while ( i-- ) {
705 // bindings[i] may have been removed by the previous step's
706 // this.off so check it still exists
707 if ( bindings[i] && bindings[i].context === context ) {
708 this.off( event, bindings[i].method, context );
709 }
710 }
711 }
712 }
713
714 return this;
715 };
716
717 }() );
718
719 /*global hasOwn */
720
721 /**
722 * @class OO.Registry
723 * @mixins OO.EventEmitter
724 *
725 * @constructor
726 */
727 oo.Registry = function OoRegistry() {
728 // Mixin constructors
729 oo.EventEmitter.call( this );
730
731 // Properties
732 this.registry = {};
733 };
734
735 /* Inheritance */
736
737 oo.mixinClass( oo.Registry, oo.EventEmitter );
738
739 /* Events */
740
741 /**
742 * @event register
743 * @param {string} name
744 * @param {Mixed} data
745 */
746
747 /* Methods */
748
749 /**
750 * Associate one or more symbolic names with some data.
751 *
752 * Only the base name will be registered, overriding any existing entry with the same base name.
753 *
754 * @param {string|string[]} name Symbolic name or list of symbolic names
755 * @param {Mixed} data Data to associate with symbolic name
756 * @fires register
757 * @throws {Error} Name argument must be a string or array
758 */
759 oo.Registry.prototype.register = function ( name, data ) {
760 var i, len;
761 if ( typeof name === 'string' ) {
762 this.registry[name] = data;
763 this.emit( 'register', name, data );
764 } else if ( Array.isArray( name ) ) {
765 for ( i = 0, len = name.length; i < len; i++ ) {
766 this.register( name[i], data );
767 }
768 } else {
769 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
770 }
771 };
772
773 /**
774 * Get data for a given symbolic name.
775 *
776 * Lookups are done using the base name.
777 *
778 * @param {string} name Symbolic name
779 * @return {Mixed|undefined} Data associated with symbolic name
780 */
781 oo.Registry.prototype.lookup = function ( name ) {
782 if ( hasOwn.call( this.registry, name ) ) {
783 return this.registry[name];
784 }
785 };
786
787 /**
788 * @class OO.Factory
789 * @extends OO.Registry
790 *
791 * @constructor
792 */
793 oo.Factory = function OoFactory() {
794 oo.Factory.parent.call( this );
795
796 // Properties
797 this.entries = [];
798 };
799
800 /* Inheritance */
801
802 oo.inheritClass( oo.Factory, oo.Registry );
803
804 /* Methods */
805
806 /**
807 * Register a constructor with the factory.
808 *
809 * Classes must have a static `name` property to be registered.
810 *
811 * function MyClass() {};
812 * OO.initClass( MyClass );
813 * // Adds a static property to the class defining a symbolic name
814 * MyClass.static.name = 'mine';
815 * // Registers class with factory, available via symbolic name 'mine'
816 * factory.register( MyClass );
817 *
818 * @param {Function} constructor Constructor to use when creating object
819 * @throws {Error} Name must be a string and must not be empty
820 * @throws {Error} Constructor must be a function
821 */
822 oo.Factory.prototype.register = function ( constructor ) {
823 var name;
824
825 if ( typeof constructor !== 'function' ) {
826 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
827 }
828 name = constructor.static && constructor.static.name;
829 if ( typeof name !== 'string' || name === '' ) {
830 throw new Error( 'Name must be a string and must not be empty' );
831 }
832 this.entries.push( name );
833
834 oo.Factory.parent.prototype.register.call( this, name, constructor );
835 };
836
837 /**
838 * Create an object based on a name.
839 *
840 * Name is used to look up the constructor to use, while all additional arguments are passed to the
841 * constructor directly, so leaving one out will pass an undefined to the constructor.
842 *
843 * @param {string} name Object name
844 * @param {Mixed...} [args] Arguments to pass to the constructor
845 * @return {Object} The new object
846 * @throws {Error} Unknown object name
847 */
848 oo.Factory.prototype.create = function ( name ) {
849 var args, obj,
850 constructor = this.lookup( name );
851
852 if ( !constructor ) {
853 throw new Error( 'No class registered by that name: ' + name );
854 }
855
856 // Convert arguments to array and shift the first argument (name) off
857 args = Array.prototype.slice.call( arguments, 1 );
858
859 // We can't use the "new" operator with .apply directly because apply needs a
860 // context. So instead just do what "new" does: create an object that inherits from
861 // the constructor's prototype (which also makes it an "instanceof" the constructor),
862 // then invoke the constructor with the object as context, and return it (ignoring
863 // the constructor's return value).
864 obj = Object.create( constructor.prototype );
865 constructor.apply( obj, args );
866 return obj;
867 };
868
869 /*jshint node:true */
870 if ( typeof module !== 'undefined' && module.exports ) {
871 module.exports = oo;
872 } else {
873 global.OO = oo;
874 }
875
876 }( this ) );