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