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