Merge "Add two hooks to allow for extensions to expose log_search values in the UI"
[lhc/web/wiklou.git] / resources / lib / oojs / oojs.jquery.js
1 /*!
2 * OOjs v1.1.2 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-11-06T17:42:36Z
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 (
257 ( aType === 'string' || aType === 'number' || aType === 'boolean' ) &&
258 aValue !== bValue
259 ) ||
260 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, asymmetrical ) ) ) {
261 return false;
262 }
263 }
264 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
265 return asymmetrical ? true : oo.compare( b, a, true );
266 };
267
268 /**
269 * Create a plain deep copy of any kind of object.
270 *
271 * Copies are deep, and will either be an object or an array depending on `source`.
272 *
273 * @param {Object} source Object to copy
274 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
275 * @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.
276 * @return {Object} Copy of source object
277 */
278 oo.copy = function ( source, leafCallback, nodeCallback ) {
279 var key, destination;
280
281 if ( nodeCallback ) {
282 // Extensibility: check before attempting to clone source.
283 destination = nodeCallback( source );
284 if ( destination !== undefined ) {
285 return destination;
286 }
287 }
288
289 if ( Array.isArray( source ) ) {
290 // Array (fall through)
291 destination = new Array( source.length );
292 } else if ( source && typeof source.clone === 'function' ) {
293 // Duck type object with custom clone method
294 return leafCallback ? leafCallback( source.clone() ) : source.clone();
295 } else if ( source && typeof source.cloneNode === 'function' ) {
296 // DOM Node
297 return leafCallback ?
298 leafCallback( source.cloneNode( true ) ) :
299 source.cloneNode( true );
300 } else if ( oo.isPlainObject( source ) ) {
301 // Plain objects (fall through)
302 destination = {};
303 } else {
304 // Non-plain objects (incl. functions) and primitive values
305 return leafCallback ? leafCallback( source ) : source;
306 }
307
308 // source is an array or a plain object
309 for ( key in source ) {
310 destination[key] = oo.copy( source[key], leafCallback, nodeCallback );
311 }
312
313 // This is an internal node, so we don't apply the leafCallback.
314 return destination;
315 };
316
317 /**
318 * Generate a hash of an object based on its name and data.
319 *
320 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
321 *
322 * To avoid two objects with the same values generating different hashes, we utilize the replacer
323 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
324 * not be the fastest way to do this; we should investigate this further.
325 *
326 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
327 * function, we call that function and use its return value rather than hashing the object
328 * ourselves. This allows classes to define custom hashing.
329 *
330 * @param {Object} val Object to generate hash for
331 * @return {string} Hash of object
332 */
333 oo.getHash = function ( val ) {
334 return JSON.stringify( val, oo.getHash.keySortReplacer );
335 };
336
337 /**
338 * Sort objects by key (helper function for OO.getHash).
339 *
340 * This is a callback passed into JSON.stringify.
341 *
342 * @method getHash_keySortReplacer
343 * @param {string} key Property name of value being replaced
344 * @param {Mixed} val Property value to replace
345 * @return {Mixed} Replacement value
346 */
347 oo.getHash.keySortReplacer = function ( key, val ) {
348 var normalized, keys, i, len;
349 if ( val && typeof val.getHashObject === 'function' ) {
350 // This object has its own custom hash function, use it
351 val = val.getHashObject();
352 }
353 if ( !Array.isArray( val ) && Object( val ) === val ) {
354 // Only normalize objects when the key-order is ambiguous
355 // (e.g. any object not an array).
356 normalized = {};
357 keys = Object.keys( val ).sort();
358 i = 0;
359 len = keys.length;
360 for ( ; i < len; i += 1 ) {
361 normalized[keys[i]] = val[keys[i]];
362 }
363 return normalized;
364
365 // Primitive values and arrays get stable hashes
366 // by default. Lets those be stringified as-is.
367 } else {
368 return val;
369 }
370 };
371
372 /**
373 * Compute the union (duplicate-free merge) of a set of arrays.
374 *
375 * Arrays values must be convertable to object keys (strings).
376 *
377 * By building an object (with the values for keys) in parallel with
378 * the array, a new item's existence in the union can be computed faster.
379 *
380 * @param {Array...} arrays Arrays to union
381 * @return {Array} Union of the arrays
382 */
383 oo.simpleArrayUnion = function () {
384 var i, ilen, arr, j, jlen,
385 obj = {},
386 result = [];
387
388 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) {
389 arr = arguments[i];
390 for ( j = 0, jlen = arr.length; j < jlen; j++ ) {
391 if ( !obj[ arr[j] ] ) {
392 obj[ arr[j] ] = true;
393 result.push( arr[j] );
394 }
395 }
396 }
397
398 return result;
399 };
400
401 /**
402 * Combine arrays (intersection or difference).
403 *
404 * An intersection checks the item exists in 'b' while difference checks it doesn't.
405 *
406 * Arrays values must be convertable to object keys (strings).
407 *
408 * By building an object (with the values for keys) of 'b' we can
409 * compute the result faster.
410 *
411 * @private
412 * @param {Array} a First array
413 * @param {Array} b Second array
414 * @param {boolean} includeB Whether to items in 'b'
415 * @return {Array} Combination (intersection or difference) of arrays
416 */
417 function simpleArrayCombine( a, b, includeB ) {
418 var i, ilen, isInB,
419 bObj = {},
420 result = [];
421
422 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
423 bObj[ b[i] ] = true;
424 }
425
426 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
427 isInB = !!bObj[ a[i] ];
428 if ( isInB === includeB ) {
429 result.push( a[i] );
430 }
431 }
432
433 return result;
434 }
435
436 /**
437 * Compute the intersection of two arrays (items in both arrays).
438 *
439 * Arrays values must be convertable to object keys (strings).
440 *
441 * @param {Array} a First array
442 * @param {Array} b Second array
443 * @return {Array} Intersection of arrays
444 */
445 oo.simpleArrayIntersection = function ( a, b ) {
446 return simpleArrayCombine( a, b, true );
447 };
448
449 /**
450 * Compute the difference of two arrays (items in 'a' but not 'b').
451 *
452 * Arrays values must be convertable to object keys (strings).
453 *
454 * @param {Array} a First array
455 * @param {Array} b Second array
456 * @return {Array} Intersection of arrays
457 */
458 oo.simpleArrayDifference = function ( a, b ) {
459 return simpleArrayCombine( a, b, false );
460 };
461
462 /*global $ */
463
464 oo.isPlainObject = $.isPlainObject;
465
466 /*global hasOwn */
467
468 ( function () {
469
470 /**
471 * @class OO.EventEmitter
472 *
473 * @constructor
474 */
475 oo.EventEmitter = function OoEventEmitter() {
476 // Properties
477
478 /**
479 * Storage of bound event handlers by event name.
480 *
481 * @property
482 */
483 this.bindings = {};
484 };
485
486 oo.initClass( oo.EventEmitter );
487
488 /* Private helper functions */
489
490 /**
491 * Validate a function or method call in a context
492 *
493 * For a method name, check that it names a function in the context object
494 *
495 * @private
496 * @param {Function|string} method Function or method name
497 * @param {Mixed} context The context of the call
498 * @throws {Error} A method name is given but there is no context
499 * @throws {Error} In the context object, no property exists with the given name
500 * @throws {Error} In the context object, the named property is not a function
501 */
502 function validateMethod( method, context ) {
503 // Validate method and context
504 if ( typeof method === 'string' ) {
505 // Validate method
506 if ( context === undefined || context === null ) {
507 throw new Error( 'Method name "' + method + '" has no context.' );
508 }
509 if ( typeof context[method] !== 'function' ) {
510 // Technically the property could be replaced by a function before
511 // call time. But this probably signals a typo.
512 throw new Error( 'Property "' + method + '" is not a function' );
513 }
514 } else if ( typeof method !== 'function' ) {
515 throw new Error( 'Invalid callback. Function or method name expected.' );
516 }
517 }
518
519 /* Methods */
520
521 /**
522 * Add a listener to events of a specific event.
523 *
524 * The listener can be a function or the string name of a method; if the latter, then the
525 * name lookup happens at the time the listener is called.
526 *
527 * @param {string} event Type of event to listen to
528 * @param {Function|string} method Function or method name to call when event occurs
529 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
530 * @param {Object} [context=null] Context object for function or method call
531 * @throws {Error} Listener argument is not a function or a valid method name
532 * @chainable
533 */
534 oo.EventEmitter.prototype.on = function ( event, method, args, context ) {
535 var bindings;
536
537 validateMethod( method, context );
538
539 if ( hasOwn.call( this.bindings, event ) ) {
540 bindings = this.bindings[event];
541 } else {
542 // Auto-initialize bindings list
543 bindings = this.bindings[event] = [];
544 }
545 // Add binding
546 bindings.push( {
547 method: method,
548 args: args,
549 context: ( arguments.length < 4 ) ? null : context
550 } );
551 return this;
552 };
553
554 /**
555 * Add a one-time listener to a specific event.
556 *
557 * @param {string} event Type of event to listen to
558 * @param {Function} listener Listener to call when event occurs
559 * @chainable
560 */
561 oo.EventEmitter.prototype.once = function ( event, listener ) {
562 var eventEmitter = this,
563 listenerWrapper = function () {
564 eventEmitter.off( event, listenerWrapper );
565 listener.apply( eventEmitter, Array.prototype.slice.call( arguments, 0 ) );
566 };
567 return this.on( event, listenerWrapper );
568 };
569
570 /**
571 * Remove a specific listener from a specific event.
572 *
573 * @param {string} event Type of event to remove listener from
574 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
575 * to "on". Omit to remove all listeners.
576 * @param {Object} [context=null] Context object function or method call
577 * @chainable
578 * @throws {Error} Listener argument is not a function or a valid method name
579 */
580 oo.EventEmitter.prototype.off = function ( event, method, context ) {
581 var i, bindings;
582
583 if ( arguments.length === 1 ) {
584 // Remove all bindings for event
585 delete this.bindings[event];
586 return this;
587 }
588
589 validateMethod( method, context );
590
591 if ( !hasOwn.call( this.bindings, event ) || !this.bindings[event].length ) {
592 // No matching bindings
593 return this;
594 }
595
596 // Default to null context
597 if ( arguments.length < 3 ) {
598 context = null;
599 }
600
601 // Remove matching handlers
602 bindings = this.bindings[event];
603 i = bindings.length;
604 while ( i-- ) {
605 if ( bindings[i].method === method && bindings[i].context === context ) {
606 bindings.splice( i, 1 );
607 }
608 }
609
610 // Cleanup if now empty
611 if ( bindings.length === 0 ) {
612 delete this.bindings[event];
613 }
614 return this;
615 };
616
617 /**
618 * Emit an event.
619 *
620 * TODO: Should this be chainable? What is the usefulness of the boolean
621 * return value here?
622 *
623 * @param {string} event Type of event
624 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
625 * @return {boolean} If event was handled by at least one listener
626 */
627 oo.EventEmitter.prototype.emit = function ( event ) {
628 var i, len, binding, bindings, args, method;
629
630 if ( hasOwn.call( this.bindings, event ) ) {
631 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
632 bindings = this.bindings[event].slice();
633 args = Array.prototype.slice.call( arguments, 1 );
634 for ( i = 0, len = bindings.length; i < len; i++ ) {
635 binding = bindings[i];
636 if ( typeof binding.method === 'string' ) {
637 // Lookup method by name (late binding)
638 method = binding.context[ binding.method ];
639 } else {
640 method = binding.method;
641 }
642 method.apply(
643 binding.context,
644 binding.args ? binding.args.concat( args ) : args
645 );
646 }
647 return true;
648 }
649 return false;
650 };
651
652 /**
653 * Connect event handlers to an object.
654 *
655 * @param {Object} context Object to call methods on when events occur
656 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
657 * event bindings keyed by event name containing either method names, functions or arrays containing
658 * method name or function followed by a list of arguments to be passed to callback before emitted
659 * arguments
660 * @chainable
661 */
662 oo.EventEmitter.prototype.connect = function ( context, methods ) {
663 var method, args, event;
664
665 for ( event in methods ) {
666 method = methods[event];
667 // Allow providing additional args
668 if ( Array.isArray( method ) ) {
669 args = method.slice( 1 );
670 method = method[0];
671 } else {
672 args = [];
673 }
674 // Add binding
675 this.on( event, method, args, context );
676 }
677 return this;
678 };
679
680 /**
681 * Disconnect event handlers from an object.
682 *
683 * @param {Object} context Object to disconnect methods from
684 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
685 * event bindings keyed by event name. Values can be either method names or functions, but must be
686 * consistent with those used in the corresponding call to "connect".
687 * @chainable
688 */
689 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
690 var i, event, bindings;
691
692 if ( methods ) {
693 // Remove specific connections to the context
694 for ( event in methods ) {
695 this.off( event, methods[event], context );
696 }
697 } else {
698 // Remove all connections to the context
699 for ( event in this.bindings ) {
700 bindings = this.bindings[event];
701 i = bindings.length;
702 while ( i-- ) {
703 // bindings[i] may have been removed by the previous step's
704 // this.off so check it still exists
705 if ( bindings[i] && bindings[i].context === context ) {
706 this.off( event, bindings[i].method, context );
707 }
708 }
709 }
710 }
711
712 return this;
713 };
714
715 }() );
716
717 /*global hasOwn */
718
719 /**
720 * @class OO.Registry
721 * @mixins OO.EventEmitter
722 *
723 * @constructor
724 */
725 oo.Registry = function OoRegistry() {
726 // Mixin constructors
727 oo.EventEmitter.call( this );
728
729 // Properties
730 this.registry = {};
731 };
732
733 /* Inheritance */
734
735 oo.mixinClass( oo.Registry, oo.EventEmitter );
736
737 /* Events */
738
739 /**
740 * @event register
741 * @param {string} name
742 * @param {Mixed} data
743 */
744
745 /* Methods */
746
747 /**
748 * Associate one or more symbolic names with some data.
749 *
750 * Only the base name will be registered, overriding any existing entry with the same base name.
751 *
752 * @param {string|string[]} name Symbolic name or list of symbolic names
753 * @param {Mixed} data Data to associate with symbolic name
754 * @fires register
755 * @throws {Error} Name argument must be a string or array
756 */
757 oo.Registry.prototype.register = function ( name, data ) {
758 var i, len;
759 if ( typeof name === 'string' ) {
760 this.registry[name] = data;
761 this.emit( 'register', name, data );
762 } else if ( Array.isArray( name ) ) {
763 for ( i = 0, len = name.length; i < len; i++ ) {
764 this.register( name[i], data );
765 }
766 } else {
767 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
768 }
769 };
770
771 /**
772 * Get data for a given symbolic name.
773 *
774 * Lookups are done using the base name.
775 *
776 * @param {string} name Symbolic name
777 * @return {Mixed|undefined} Data associated with symbolic name
778 */
779 oo.Registry.prototype.lookup = function ( name ) {
780 if ( hasOwn.call( this.registry, name ) ) {
781 return this.registry[name];
782 }
783 };
784
785 /**
786 * @class OO.Factory
787 * @extends OO.Registry
788 *
789 * @constructor
790 */
791 oo.Factory = function OoFactory() {
792 oo.Factory.parent.call( this );
793
794 // Properties
795 this.entries = [];
796 };
797
798 /* Inheritance */
799
800 oo.inheritClass( oo.Factory, oo.Registry );
801
802 /* Methods */
803
804 /**
805 * Register a constructor with the factory.
806 *
807 * Classes must have a static `name` property to be registered.
808 *
809 * function MyClass() {};
810 * OO.initClass( MyClass );
811 * // Adds a static property to the class defining a symbolic name
812 * MyClass.static.name = 'mine';
813 * // Registers class with factory, available via symbolic name 'mine'
814 * factory.register( MyClass );
815 *
816 * @param {Function} constructor Constructor to use when creating object
817 * @throws {Error} Name must be a string and must not be empty
818 * @throws {Error} Constructor must be a function
819 */
820 oo.Factory.prototype.register = function ( constructor ) {
821 var name;
822
823 if ( typeof constructor !== 'function' ) {
824 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
825 }
826 name = constructor.static && constructor.static.name;
827 if ( typeof name !== 'string' || name === '' ) {
828 throw new Error( 'Name must be a string and must not be empty' );
829 }
830 this.entries.push( name );
831
832 oo.Factory.parent.prototype.register.call( this, name, constructor );
833 };
834
835 /**
836 * Create an object based on a name.
837 *
838 * Name is used to look up the constructor to use, while all additional arguments are passed to the
839 * constructor directly, so leaving one out will pass an undefined to the constructor.
840 *
841 * @param {string} name Object name
842 * @param {Mixed...} [args] Arguments to pass to the constructor
843 * @return {Object} The new object
844 * @throws {Error} Unknown object name
845 */
846 oo.Factory.prototype.create = function ( name ) {
847 var args, obj,
848 constructor = this.lookup( name );
849
850 if ( !constructor ) {
851 throw new Error( 'No class registered by that name: ' + name );
852 }
853
854 // Convert arguments to array and shift the first argument (name) off
855 args = Array.prototype.slice.call( arguments, 1 );
856
857 // We can't use the "new" operator with .apply directly because apply needs a
858 // context. So instead just do what "new" does: create an object that inherits from
859 // the constructor's prototype (which also makes it an "instanceof" the constructor),
860 // then invoke the constructor with the object as context, and return it (ignoring
861 // the constructor's return value).
862 obj = Object.create( constructor.prototype );
863 constructor.apply( obj, args );
864 return obj;
865 };
866
867 /*jshint node:true */
868 if ( typeof module !== 'undefined' && module.exports ) {
869 module.exports = oo;
870 } else {
871 global.OO = oo;
872 }
873
874 }( this ) );