Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Last active November 17, 2015 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosascari/fa88c988fe30d556ee2c to your computer and use it in GitHub Desktop.
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)
/**
* 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