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