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