Skip to content

Instantly share code, notes, and snippets.

@rudylattae
Created January 18, 2014 06:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rudylattae/8487090 to your computer and use it in GitHub Desktop.
Save rudylattae/8487090 to your computer and use it in GitHub Desktop.
var MicroEvent = function(){};
MicroEvent.prototype = {
bind : function(event, fct){
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
},
once: function(event, fct){
var wrapped = function() {
this.unbind(event, fct);
this.unbind(event, wrapped);
}
this.bind(event, fct);
this.bind(event, wrapped);
},
unbind : function(event, fct){
this._events = this._events || {};
if( event in this._events === false ) return;
this._events[event].splice(this._events[event].indexOf(fct), 1);
},
trigger : 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));
}
}
};
/**
* mixin will delegate all MicroEvent.js function in the destination object
*
* - require('MicroEvent').mixin(Foobar) will make Foobar able to use MicroEvent
*
* @param {Object} the object which will support MicroEvent
*/
MicroEvent.mixin = function(destObject){
var props = ['bind', 'once', 'unbind', 'trigger'];
for(var i = 0; i < props.length; i ++){
if( typeof destObject === 'function' ){
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
}else{
destObject[props[i]] = MicroEvent.prototype[props[i]];
}
}
}
// Add some method aliases.
MicroEvent.prototype.on = MicroEvent.prototype.bind;
MicroEvent.prototype.off = MicroEvent.prototype.unbind;
MicroEvent.prototype.emit = MicroEvent.prototype.trigger;
// export in common js
if( typeof module !== "undefined" && ('exports' in module)){
module.exports = MicroEvent;
}
// AMD support
if( typeof define !== "undefined"){
define([], function(){
return MicroEvent;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment