Created
January 18, 2014 06:42
-
-
Save rudylattae/8487090 to your computer and use it in GitHub Desktop.
JS events -- original https://github.com/jeromeetienne/microevent.js with augmentations from https://github.com/jeromeetienne/microevent.js/network
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
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