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