Localisation updates from https://translatewiki.net.
[mediawiki.git] / resources / oojs / oojs.js
blobd2d61e9ad2bc58f062af92ceab512e85e7a391ad
1 /*!
2 * Object Oriented JavaScript Library v1.0.5
3 * https://github.com/trevorparscal/oojs
5 * Copyright 2011-2013 OOJS Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: Wed Oct 23 2013 02:22:02 GMT+0200 (CEST)
11 ( function ( global ) {
13 'use strict';
14 var
15 /**
16 * Namespace for all classes, static methods and static properties.
17 * @class OO
18 * @singleton
20 oo = {},
21 hasOwn = oo.hasOwnProperty,
22 toString = oo.toString;
24 /* Class Methods */
27 /**
28 * Assert whether a value is a plain object or not.
30 * @method
31 * @param {Mixed} obj
32 * @return {boolean}
34 oo.isPlainObject = function ( obj ) {
35 // Any object or value whose internal [[Class]] property is not "[object Object]"
36 if ( toString.call( obj ) !== '[object Object]' ) {
37 return false;
40 // The try/catch suppresses exceptions thrown when attempting to access
41 // the "constructor" property of certain host objects suich as window.location
42 // in Firefox < 20 (https://bugzilla.mozilla.org/814622)
43 try {
44 if ( obj.constructor &&
45 !hasOwn.call( obj.constructor.prototype, 'isPrototypeOf' ) ) {
46 return false;
48 } catch ( e ) {
49 return false;
52 return true;
55 /**
56 * Utility for common usage of Object#create for inheriting from one
57 * prototype to another.
59 * Beware: This redefines the prototype, call before setting your prototypes.
60 * Beware: This redefines the prototype, can only be called once on a function.
61 * If called multiple times on the same function, the previous prototype is lost.
62 * This is how prototypal inheritance works, it can only be one straight chain
63 * (just like classical inheritance in PHP for example). If you need to work with
64 * multiple constructors consider storing an instance of the other constructor in a
65 * property instead, or perhaps use a mixin (see oo.mixinClass).
67 * function Foo() {}
68 * Foo.prototype.jump = function () {};
70 * function FooBar() {}
71 * oo.inheritClass( FooBar, Foo );
72 * FooBar.prop.feet = 2;
73 * FooBar.prototype.walk = function () {};
75 * function FooBarQuux() {}
76 * OO.inheritClass( FooBarQuux, FooBar );
77 * FooBarQuux.prototype.jump = function () {};
79 * FooBarQuux.prop.feet === 2;
80 * var fb = new FooBar();
81 * fb.jump();
82 * fb.walk();
83 * fb instanceof Foo && fb instanceof FooBar && fb instanceof FooBarQuux;
85 * @method
86 * @param {Function} targetFn
87 * @param {Function} originFn
88 * @throws {Error} If target already inherits from origin
90 oo.inheritClass = function ( targetFn, originFn ) {
91 if ( targetFn.prototype instanceof originFn ) {
92 throw new Error( 'Target already inherits from origin' );
95 var targetConstructor = targetFn.prototype.constructor;
97 targetFn.prototype = Object.create( originFn.prototype, {
98 // Restore constructor property of targetFn
99 constructor: {
100 value: targetConstructor,
101 enumerable: false,
102 writable: true,
103 configurable: true
105 } );
107 // Extend static properties - always initialize both sides
108 originFn.static = originFn.static || {};
109 targetFn.static = Object.create( originFn.static );
113 * Utility to copy over *own* prototype properties of a mixin.
114 * The 'constructor' (whether implicit or explicit) is not copied over.
116 * This does not create inheritance to the origin. If inheritance is needed
117 * use oo.inheritClass instead.
119 * Beware: This can redefine a prototype property, call before setting your prototypes.
120 * Beware: Don't call before oo.inheritClass.
122 * function Foo() {}
123 * function Context() {}
125 * // Avoid repeating this code
126 * function ContextLazyLoad() {}
127 * ContextLazyLoad.prototype.getContext = function () {
128 * if ( !this.context ) {
129 * this.context = new Context();
131 * return this.context;
132 * };
134 * function FooBar() {}
135 * OO.inheritClass( FooBar, Foo );
136 * OO.mixinClass( FooBar, ContextLazyLoad );
138 * @method
139 * @param {Function} targetFn
140 * @param {Function} originFn
142 oo.mixinClass = function ( targetFn, originFn ) {
143 var key;
145 // Copy prototype properties
146 for ( key in originFn.prototype ) {
147 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) {
148 targetFn.prototype[key] = originFn.prototype[key];
152 // Copy static properties - always initialize both sides
153 targetFn.static = targetFn.static || {};
154 if ( originFn.static ) {
155 for ( key in originFn.static ) {
156 if ( hasOwn.call( originFn.static, key ) ) {
157 targetFn.static[key] = originFn.static[key];
160 } else {
161 originFn.static = {};
165 /* Object Methods */
168 * Create a new object that is an instance of the same
169 * constructor as the input, inherits from the same object
170 * and contains the same own properties.
172 * This makes a shallow non-recursive copy of own properties.
173 * To create a recursive copy of plain objects, use #copy.
175 * var foo = new Person( mom, dad );
176 * foo.setAge( 21 );
177 * var foo2 = OO.cloneObject( foo );
178 * foo.setAge( 22 );
180 * // Then
181 * foo2 !== foo; // true
182 * foo2 instanceof Person; // true
183 * foo2.getAge(); // 21
184 * foo.getAge(); // 22
186 * @method
187 * @param {Object} origin
188 * @return {Object} Clone of origin
190 oo.cloneObject = function ( origin ) {
191 var key, r;
193 r = Object.create( origin.constructor.prototype );
195 for ( key in origin ) {
196 if ( hasOwn.call( origin, key ) ) {
197 r[key] = origin[key];
201 return r;
205 * Gets an array of all property values in an object.
207 * @method
208 * @param {Object} Object to get values from
209 * @returns {Array} List of object values
211 oo.getObjectValues = function ( obj ) {
212 var key, values;
214 if ( obj !== Object( obj ) ) {
215 throw new TypeError( 'Called on non-object' );
218 values = [];
219 for ( key in obj ) {
220 if ( hasOwn.call( obj, key ) ) {
221 values[values.length] = obj[key];
225 return values;
229 * Recursively compares properties between two objects.
231 * A false result may be caused by property inequality or by properties in one object missing from
232 * the other. An asymmetrical test may also be performed, which checks only that properties in the
233 * first object are present in the second object, but not the inverse.
235 * @method
236 * @param {Object} a First object to compare
237 * @param {Object} b Second object to compare
238 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
239 * @returns {boolean} If the objects contain the same values as each other
241 oo.compare = function ( a, b, asymmetrical ) {
242 var aValue, bValue, aType, bType, k;
244 if ( a === b ) {
245 return true;
248 for ( k in a ) {
249 aValue = a[k];
250 bValue = b[k];
251 aType = typeof aValue;
252 bType = typeof bValue;
253 if ( aType !== bType ||
254 ( ( aType === 'string' || aType === 'number' ) && aValue !== bValue ) ||
255 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, asymmetrical ) ) ) {
256 return false;
259 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
260 return asymmetrical ? true : oo.compare( b, a, true );
264 * Create a plain deep copy of any kind of object.
266 * Copies are deep, and will either be an object or an array depending on `source`.
268 * @method
269 * @param {Object} source Object to copy
270 * @param {Function} [callback] Applied to leaf values before they added to the clone
271 * @returns {Object} Copy of source object
273 oo.copy = function ( source, callback ) {
274 var key, sourceValue, sourceType, destination;
276 if ( typeof source.clone === 'function' ) {
277 return source.clone();
280 destination = Array.isArray( source ) ? new Array( source.length ) : {};
282 for ( key in source ) {
283 sourceValue = source[key];
284 sourceType = typeof sourceValue;
285 if ( Array.isArray( sourceValue ) ) {
286 // Array
287 destination[key] = oo.copy( sourceValue, callback );
288 } else if ( sourceValue && typeof sourceValue.clone === 'function' ) {
289 // Duck type object with custom clone method
290 destination[key] = callback ?
291 callback( sourceValue.clone() ) : sourceValue.clone();
292 } else if ( sourceValue && typeof sourceValue.cloneNode === 'function' ) {
293 // DOM Node
294 destination[key] = callback ?
295 callback( sourceValue.cloneNode( true ) ) : sourceValue.cloneNode( true );
296 } else if ( oo.isPlainObject( sourceValue ) ) {
297 // Plain objects
298 destination[key] = oo.copy( sourceValue, callback );
299 } else {
300 // Non-plain objects (incl. functions) and primitive values
301 destination[key] = callback ? callback( sourceValue ) : sourceValue;
305 return destination;
309 * Generates a hash of an object based on its name and data.
310 * Performance optimization: http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse
312 * To avoid two objects with the same values generating different hashes, we utilize the replacer
313 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
314 * not be the fastest way to do this; we should investigate this further.
316 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
317 * function, we call that function and use its return value rather than hashing the object
318 * ourselves. This allows classes to define custom hashing.
320 * @param {Object} val Object to generate hash for
321 * @returns {string} Hash of object
323 oo.getHash = function ( val ) {
324 return JSON.stringify( val, oo.getHash.keySortReplacer );
328 * Helper function for oo.getHash which sorts objects by key.
330 * This is a callback passed into JSON.stringify.
332 * @param {string} key Property name of value being replaced
333 * @param {Mixed} val Property value to replace
334 * @returns {Mixed} Replacement value
336 oo.getHash.keySortReplacer = function ( key, val ) {
337 var normalized, keys, i, len;
338 if ( val && typeof val.getHashObject === 'function' ) {
339 // This object has its own custom hash function, use it
340 val = val.getHashObject();
342 if ( !Array.isArray( val ) && Object( val ) === val ) {
343 // Only normalize objects when the key-order is ambiguous
344 // (e.g. any object not an array).
345 normalized = {};
346 keys = Object.keys( val ).sort();
347 i = 0;
348 len = keys.length;
349 for ( ; i < len; i += 1 ) {
350 normalized[keys[i]] = val[keys[i]];
352 return normalized;
354 // Primitive values and arrays get stable hashes
355 // by default. Lets those be stringified as-is.
356 } else {
357 return val;
362 * Compute the union (duplicate-free merge) of a set of arrays.
364 * Arrays values must be convertable to object keys (strings)
366 * By building an object (with the values for keys) in parallel with
367 * the array, a new item's existence in the union can be computed faster
369 * @param {Array...} arrays Arrays to union
370 * @returns {Array} Union of the arrays
372 oo.simpleArrayUnion = function () {
373 var i, ilen, arr, j, jlen,
374 obj = {},
375 result = [];
377 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) {
378 arr = arguments[i];
379 for ( j = 0, jlen = arr.length; j < jlen; j++ ) {
380 if ( !obj[ arr[j] ] ) {
381 obj[ arr[j] ] = true;
382 result.push( arr[j] );
387 return result;
391 * Combine arrays (intersection or difference).
393 * An intersection checks the item exists in 'b' while difference checks it doesn't.
395 * Arrays values must be convertable to object keys (strings)
397 * By building an object (with the values for keys) of 'b' we can
398 * compute the result faster
400 * @private
401 * @param {Array} a First array
402 * @param {Array} b Second array
403 * @param {boolean} includeB Whether to items in 'b'
404 * @returns {Array} Combination (intersection or difference) of arrays
406 function simpleArrayCombine( a, b, includeB ) {
407 var i, ilen, isInB,
408 bObj = {},
409 result = [];
411 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
412 bObj[ b[i] ] = true;
415 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
416 isInB = !!bObj[ a[i] ];
417 if ( isInB === includeB ) {
418 result.push( a[i] );
422 return result;
426 * Compute the intersection of two arrays (items in both arrays).
428 * Arrays values must be convertable to object keys (strings)
430 * @param {Array} a First array
431 * @param {Array} b Second array
432 * @returns {Array} Intersection of arrays
434 oo.simpleArrayIntersection = function ( a, b ) {
435 return simpleArrayCombine( a, b, true );
439 * Compute the difference of two arrays (items in 'a' but not 'b').
441 * Arrays values must be convertable to object keys (strings)
443 * @param {Array} a First array
444 * @param {Array} b Second array
445 * @returns {Array} Intersection of arrays
447 oo.simpleArrayDifference = function ( a, b ) {
448 return simpleArrayCombine( a, b, false );
451 * Event emitter.
453 * @class OO.EventEmitter
455 * @constructor
456 * @property {Object} bindings
458 oo.EventEmitter = function OoEventEmitter() {
459 // Properties
460 this.bindings = {};
463 /* Methods */
466 * Add a listener to events of a specific event.
468 * If the callback/context are already bound to the event, they will not be bound again.
470 * @method
471 * @param {string} event Type of event to listen to
472 * @param {Function} callback Function to call when event occurs
473 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
474 * @param {Object} [context=null] Object to use as context for callback function or call method on
475 * @throws {Error} Listener argument is not a function or method name
476 * @chainable
478 oo.EventEmitter.prototype.on = function ( event, callback, args, context ) {
479 var i, bindings, binding;
481 // Validate callback
482 if ( typeof callback !== 'function' ) {
483 throw new Error( 'Invalid callback. Function or method name expected.' );
485 // Fallback to null context
486 if ( arguments.length < 4 ) {
487 context = null;
489 if ( this.bindings.hasOwnProperty( event ) ) {
490 // Check for duplicate callback and context for this event
491 bindings = this.bindings[event];
492 i = bindings.length;
493 while ( i-- ) {
494 binding = bindings[i];
495 if ( bindings.callback === callback && bindings.context === context ) {
496 return this;
499 } else {
500 // Auto-initialize bindings list
501 bindings = this.bindings[event] = [];
503 // Add binding
504 bindings.push( {
505 'callback': callback,
506 'args': args,
507 'context': context
508 } );
509 return this;
513 * Adds a one-time listener to a specific event.
515 * @method
516 * @param {string} event Type of event to listen to
517 * @param {Function} listener Listener to call when event occurs
518 * @chainable
520 oo.EventEmitter.prototype.once = function ( event, listener ) {
521 var eventEmitter = this;
522 return this.on( event, function listenerWrapper() {
523 eventEmitter.off( event, listenerWrapper );
524 listener.apply( eventEmitter, Array.prototype.slice.call( arguments, 0 ) );
525 } );
529 * Remove a specific listener from a specific event.
531 * @method
532 * @param {string} event Type of event to remove listener from
533 * @param {Function} [callback] Listener to remove, omit to remove all
534 * @param {Object} [context=null] Object used context for callback function or method
535 * @chainable
536 * @throws {Error} Listener argument is not a function
538 oo.EventEmitter.prototype.off = function ( event, callback, context ) {
539 var i, bindings;
541 if ( arguments.length === 1 ) {
542 // Remove all bindings for event
543 if ( event in this.bindings ) {
544 delete this.bindings[event];
546 } else {
547 if ( typeof callback !== 'function' ) {
548 throw new Error( 'Invalid callback. Function expected.' );
550 if ( !( event in this.bindings ) || !this.bindings[event].length ) {
551 // No matching bindings
552 return this;
554 // Fallback to null context
555 if ( arguments.length < 3 ) {
556 context = null;
558 // Remove matching handlers
559 bindings = this.bindings[event];
560 i = bindings.length;
561 while ( i-- ) {
562 if ( bindings[i].callback === callback && bindings[i].context === context ) {
563 bindings.splice( i, 1 );
566 // Cleanup if now empty
567 if ( bindings.length === 0 ) {
568 delete this.bindings[event];
571 return this;
575 * Emit an event.
576 * TODO: Should this be chainable? What is the usefulness of the boolean
577 * return value here?
579 * @method
580 * @param {string} event Type of event
581 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
582 * @returns {boolean} If event was handled by at least one listener
584 oo.EventEmitter.prototype.emit = function ( event ) {
585 var i, len, binding, bindings, args;
587 if ( event in this.bindings ) {
588 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
589 bindings = this.bindings[event].slice();
590 args = Array.prototype.slice.call( arguments, 1 );
591 for ( i = 0, len = bindings.length; i < len; i++ ) {
592 binding = bindings[i];
593 binding.callback.apply(
594 binding.context,
595 binding.args ? binding.args.concat( args ) : args
598 return true;
600 return false;
604 * Connect event handlers to an object.
606 * @method
607 * @param {Object} context Object to call methods on when events occur
608 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
609 * event bindings keyed by event name containing either method names, functions or arrays containing
610 * method name or function followed by a list of arguments to be passed to callback before emitted
611 * arguments
612 * @chainable
614 oo.EventEmitter.prototype.connect = function ( context, methods ) {
615 var method, callback, args, event;
617 for ( event in methods ) {
618 method = methods[event];
619 // Allow providing additional args
620 if ( Array.isArray( method ) ) {
621 args = method.slice( 1 );
622 method = method[0];
623 } else {
624 args = [];
626 // Allow callback to be a method name
627 if ( typeof method === 'string' ) {
628 // Validate method
629 if ( !context[method] || typeof context[method] !== 'function' ) {
630 throw new Error( 'Method not found: ' + method );
632 // Resolve to function
633 callback = context[method];
634 } else {
635 callback = method;
637 // Add binding
638 this.on.apply( this, [ event, callback, args, context ] );
640 return this;
644 * Disconnect event handlers from an object.
646 * @method
647 * @param {Object} context Object to disconnect methods from
648 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
649 * event bindings keyed by event name containing either method names or functions
650 * @chainable
652 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
653 var i, method, callback, event, bindings;
655 if ( methods ) {
656 // Remove specific connections to the context
657 for ( event in methods ) {
658 method = methods[event];
659 if ( typeof method === 'string' ) {
660 // Validate method
661 if ( !context[method] || typeof context[method] !== 'function' ) {
662 throw new Error( 'Method not found: ' + method );
664 // Resolve to function
665 callback = context[method];
666 } else {
667 callback = method;
669 this.off( event, callback, context );
671 } else {
672 // Remove all connections to the context
673 for ( event in this.bindings ) {
674 bindings = this.bindings[event];
675 i = bindings.length;
676 while ( i-- ) {
677 if ( bindings[i].context === context ) {
678 this.off( event, bindings[i].callback, context );
684 return this;
687 * Data registry.
689 * @class OO.Registry
690 * @mixins OO.EventEmitter
692 * @constructor
694 oo.Registry = function OoRegistry() {
695 // Mixin constructors
696 oo.EventEmitter.call( this );
698 // Properties
699 this.registry = {};
702 /* Inheritance */
704 oo.mixinClass( oo.Registry, oo.EventEmitter );
706 /* Events */
709 * @event register
710 * @param {string} name
711 * @param {Mixed} data
714 /* Methods */
717 * Associate one or more symbolic names with some data.
719 * Only the base name will be registered, overriding any existing entry with the same base name.
721 * @method
722 * @param {string|string[]} name Symbolic name or list of symbolic names
723 * @param {Mixed} data Data to associate with symbolic name
724 * @fires register
725 * @throws {Error} Name argument must be a string or array
727 oo.Registry.prototype.register = function ( name, data ) {
728 if ( typeof name !== 'string' && !Array.isArray( name ) ) {
729 throw new Error( 'Name argument must be a string or array, cannot be a ' + typeof name );
731 var i, len;
732 if ( Array.isArray( name ) ) {
733 for ( i = 0, len = name.length; i < len; i++ ) {
734 this.register( name[i], data );
736 } else if ( typeof name === 'string' ) {
737 this.registry[name] = data;
738 this.emit( 'register', name, data );
739 } else {
740 throw new Error( 'Name must be a string or array of strings, cannot be a ' + typeof name );
745 * Gets data for a given symbolic name.
747 * Lookups are done using the base name.
749 * @method
750 * @param {string} name Symbolic name
751 * @returns {Mixed|undefined} Data associated with symbolic name
753 oo.Registry.prototype.lookup = function ( name ) {
754 return this.registry[name];
757 * Object factory.
759 * @class OO.Factory
760 * @extends OO.Registry
762 * @constructor
764 oo.Factory = function OoFactory() {
765 // Parent constructor
766 oo.Registry.call( this );
768 // Properties
769 this.entries = [];
772 /* Inheritance */
774 oo.inheritClass( oo.Factory, oo.Registry );
776 /* Methods */
779 * Register a constructor with the factory.
781 * Classes must have a static `name` property to be registered.
783 * @example
784 * function MyClass() {};
785 * // Adds a static property to the class defining a symbolic name
786 * MyClass.static = { 'name': 'mine' };
787 * // Registers class with factory, available via symbolic name 'mine'
788 * factory.register( MyClass );
790 * @method
791 * @param {Function} constructor Constructor to use when creating object
792 * @throws {Error} Name must be a string and must not be empty
793 * @throws {Error} Constructor must be a function
795 oo.Factory.prototype.register = function ( constructor ) {
796 var name;
798 if ( typeof constructor !== 'function' ) {
799 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
801 name = constructor.static && constructor.static.name;
802 if ( typeof name !== 'string' || name === '' ) {
803 throw new Error( 'Name must be a string and must not be empty' );
805 this.entries.push( name );
806 oo.Registry.prototype.register.call( this, name, constructor );
810 * Create an object based on a name.
812 * Name is used to look up the constructor to use, while all additional arguments are passed to the
813 * constructor directly, so leaving one out will pass an undefined to the constructor.
815 * @method
816 * @param {string} name Object name
817 * @param {Mixed...} [args] Arguments to pass to the constructor
818 * @returns {Object} The new object
819 * @throws {Error} Unknown object name
821 oo.Factory.prototype.create = function ( name ) {
822 var args, obj, constructor;
824 if ( !this.registry.hasOwnProperty( name ) ) {
825 throw new Error( 'No class registered by that name: ' + name );
827 constructor = this.registry[name];
829 // Convert arguments to array and shift the first argument (name) off
830 args = Array.prototype.slice.call( arguments, 1 );
832 // We can't use the "new" operator with .apply directly because apply needs a
833 // context. So instead just do what "new" does: create an object that inherits from
834 // the constructor's prototype (which also makes it an "instanceof" the constructor),
835 // then invoke the constructor with the object as context, and return it (ignoring
836 // the constructor's return value).
837 obj = Object.create( constructor.prototype );
838 constructor.apply( obj, args );
839 return obj;
841 /*jshint node:true */
842 if ( typeof module !== 'undefined' && module.exports ) {
843 module.exports = oo;
844 } else {
845 global.OO = oo;
847 }( this ) );