Created
July 1, 2011 08:30
-
-
Save mattijs/1058095 to your computer and use it in GitHub Desktop.
Browser Side Event Emitter
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
/** | |
* Small EventEmitter implementation borowed from MicroEvent.js | |
* | |
* MicroEvent.js: https://github.com/jeromeetienne/microevent.js | |
*/ | |
var Emitter = function(){}; | |
Emitter.prototype = { | |
on: function(event, fct){ | |
this._events = this._events || {}; | |
this._events[event] = this._events[event] || []; | |
this._events[event].push(fct); | |
}, | |
removeListener: function(event, fct){ | |
this._events = this._events || {}; | |
if( event in this._events === false ) return; | |
this._events[event].splice(this._events[event].indexOf(fct), 1); | |
}, | |
emit: function(event /* , args... */){ | |
this._events = this._events || {}; | |
if( event in this._events === false ) return; | |
for(var i = 0; i < this._events[event].length; i++){ | |
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); | |
} | |
} | |
}; | |
/** | |
* Enable will delegate all Emitter function in the destination object | |
* | |
* Emitter.enable(Foobar) will make Foobar able to act as an EventEmitter | |
*/ | |
Emitter.enable = function(destObject){ | |
var props = ['on', 'removeListener', 'emit']; | |
for(var i = 0; i < props.length; i ++){ | |
destObject.prototype[props[i]] = Emitter.prototype[props[i]]; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment