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
) {
16 * Namespace for all classes, static methods and static properties.
21 hasOwn
= oo
.hasOwnProperty
,
22 toString
= oo
.toString
;
28 * Assert whether a value is a plain object or not.
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]' ) {
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)
44 if ( obj
.constructor &&
45 !hasOwn
.call( obj
.constructor.prototype, 'isPrototypeOf' ) ) {
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).
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();
83 * fb instanceof Foo && fb instanceof FooBar && fb instanceof FooBarQuux;
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
100 value
: targetConstructor
,
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.
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;
134 * function FooBar() {}
135 * OO.inheritClass( FooBar, Foo );
136 * OO.mixinClass( FooBar, ContextLazyLoad );
139 * @param {Function} targetFn
140 * @param {Function} originFn
142 oo
.mixinClass = function ( targetFn
, originFn
) {
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
];
161 originFn
.static = {};
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 );
177 * var foo2 = OO.cloneObject( foo );
181 * foo2 !== foo; // true
182 * foo2 instanceof Person; // true
183 * foo2.getAge(); // 21
184 * foo.getAge(); // 22
187 * @param {Object} origin
188 * @return {Object} Clone of origin
190 oo
.cloneObject = function ( origin
) {
193 r
= Object
.create( origin
.constructor.prototype );
195 for ( key
in origin
) {
196 if ( hasOwn
.call( origin
, key
) ) {
197 r
[key
] = origin
[key
];
205 * Gets an array of all property values in an object.
208 * @param {Object} Object to get values from
209 * @returns {Array} List of object values
211 oo
.getObjectValues = function ( obj
) {
214 if ( obj
!== Object( obj
) ) {
215 throw new TypeError( 'Called on non-object' );
220 if ( hasOwn
.call( obj
, key
) ) {
221 values
[values
.length
] = obj
[key
];
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.
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
;
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
) ) ) {
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`.
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
) ) {
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' ) {
294 destination
[key
] = callback
?
295 callback( sourceValue
.cloneNode( true ) ) : sourceValue
.cloneNode( true );
296 } else if ( oo
.isPlainObject( sourceValue
) ) {
298 destination
[key
] = oo
.copy( sourceValue
, callback
);
300 // Non-plain objects (incl. functions) and primitive values
301 destination
[key
] = callback
? callback( sourceValue
) : sourceValue
;
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).
346 keys
= Object
.keys( val
).sort();
349 for ( ; i
< len
; i
+= 1 ) {
350 normalized
[keys
[i
]] = val
[keys
[i
]];
354 // Primitive values and arrays get stable hashes
355 // by default. Lets those be stringified as-is.
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
,
377 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; 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
] );
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
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
) {
411 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
415 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
416 isInB
= !!bObj
[ a
[i
] ];
417 if ( isInB
=== includeB
) {
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 );
453 * @class OO.EventEmitter
456 * @property {Object} bindings
458 oo
.EventEmitter
= function OoEventEmitter() {
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.
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
478 oo
.EventEmitter
.prototype.on = function ( event
, callback
, args
, context
) {
479 var i
, bindings
, binding
;
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 ) {
489 if ( this.bindings
.hasOwnProperty( event
) ) {
490 // Check for duplicate callback and context for this event
491 bindings
= this.bindings
[event
];
494 binding
= bindings
[i
];
495 if ( bindings
.callback
=== callback
&& bindings
.context
=== context
) {
500 // Auto-initialize bindings list
501 bindings
= this.bindings
[event
] = [];
505 'callback': callback
,
513 * Adds a one-time listener to a specific event.
516 * @param {string} event Type of event to listen to
517 * @param {Function} listener Listener to call when event occurs
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 ) );
529 * Remove a specific listener from a specific event.
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
536 * @throws {Error} Listener argument is not a function
538 oo
.EventEmitter
.prototype.off = function ( event
, callback
, context
) {
541 if ( arguments
.length
=== 1 ) {
542 // Remove all bindings for event
543 if ( event
in this.bindings
) {
544 delete this.bindings
[event
];
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
554 // Fallback to null context
555 if ( arguments
.length
< 3 ) {
558 // Remove matching handlers
559 bindings
= this.bindings
[event
];
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
];
576 * TODO: Should this be chainable? What is the usefulness of the boolean
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(
595 binding
.args
? binding
.args
.concat( args
) : args
604 * Connect event handlers to an object.
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
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 );
626 // Allow callback to be a method name
627 if ( typeof method
=== 'string' ) {
629 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
630 throw new Error( 'Method not found: ' + method
);
632 // Resolve to function
633 callback
= context
[method
];
638 this.on
.apply( this, [ event
, callback
, args
, context
] );
644 * Disconnect event handlers from an object.
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
652 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
653 var i
, method
, callback
, event
, bindings
;
656 // Remove specific connections to the context
657 for ( event
in methods
) {
658 method
= methods
[event
];
659 if ( typeof method
=== 'string' ) {
661 if ( !context
[method
] || typeof context
[method
] !== 'function' ) {
662 throw new Error( 'Method not found: ' + method
);
664 // Resolve to function
665 callback
= context
[method
];
669 this.off( event
, callback
, context
);
672 // Remove all connections to the context
673 for ( event
in this.bindings
) {
674 bindings
= this.bindings
[event
];
677 if ( bindings
[i
].context
=== context
) {
678 this.off( event
, bindings
[i
].callback
, context
);
690 * @mixins OO.EventEmitter
694 oo
.Registry
= function OoRegistry() {
695 // Mixin constructors
696 oo
.EventEmitter
.call( this );
704 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
710 * @param {string} name
711 * @param {Mixed} data
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.
722 * @param {string|string[]} name Symbolic name or list of symbolic names
723 * @param {Mixed} data Data to associate with symbolic name
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
);
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
);
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.
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
];
760 * @extends OO.Registry
764 oo
.Factory
= function OoFactory() {
765 // Parent constructor
766 oo
.Registry
.call( this );
774 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
779 * Register a constructor with the factory.
781 * Classes must have a static `name` property to be registered.
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 );
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 ) {
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.
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
);
841 /*jshint node:true */
842 if ( typeof module
!== 'undefined' && module
.exports
) {