Last active
November 17, 2015 22:52
-
-
Save carlosascari/fa88c988fe30d556ee2c to your computer and use it in GitHub Desktop.
Abstract class to add Event Emitter functionality for decoupling objects, setting up patterns (PubSub, Mediator, Observer)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides Event Emitter functionality | |
* | |
* Allows decoupling existing classes/prototypes | |
* Events are emitted in Sync. | |
* | |
* Usage | |
* @example | |
* | |
* function YourClass() | |
* { | |
* EventEmitterBehaviour.constructor.call(this) | |
* } | |
* | |
* YourClass.prototype = new EventEmitterBehaviour() | |
* | |
* @module EventEmitterBehaviour | |
*/ | |
var EventEmitterBehaviour = (function () { | |
/** | |
* @class EventEmitterBehaviour | |
* @constructor | |
*/ | |
function EventEmitterBehaviour() | |
{ | |
Object.defineProperty(this, '_events', { | |
configurable: false, | |
enumerable: false, | |
value: {} | |
}) | |
} | |
/** | |
* Emits an event | |
* | |
* @method emit | |
* @param evt {String} | |
* @param ... {Mixed} | |
*/ | |
EventEmitterBehaviour.prototype.emit = function(evt) | |
{ | |
if (this._events[evt] && this._events[evt].length) | |
{ | |
var args = Array.prototype.slice.call(arguments, 1) | |
var count = this._events[evt].length | |
for (var i = 0; i <count; i++) { | |
this._events[evt][i].apply(this, args) | |
} | |
} | |
return this | |
} | |
/** | |
* Subscribe to a event | |
* | |
* @method on | |
* @param evt {String} | |
* @param callback {Function} | |
*/ | |
EventEmitterBehaviour.prototype.on = function(evt, callback) | |
{ | |
if (Object.prototype.toString.call(this._events[evt]) === '[object Array]') | |
{ | |
this._events[evt].push(callback) | |
} | |
else | |
{ | |
this._events[evt] = [callback] | |
} | |
return this | |
} | |
/** | |
* Unsubscribes from a event | |
* | |
* @method off | |
* @param evt {String} | |
* @param [callback] {Function} | |
*/ | |
EventEmitterBehaviour.prototype.off = function(evt, callback) | |
{ | |
if (this._events[evt] && this._events[evt].length) | |
{ | |
if (typeof callback === 'function') | |
{ | |
this._events[evt].splice(this._events[evt].indexOf(callback), 1) | |
} | |
else | |
{ | |
this._events[evt] = [] | |
} | |
} | |
return this | |
} | |
// expose | |
return EventEmitterBehaviour | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment