Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 31 additions & 26 deletions microevent.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* MicroEvent - to make any js object an event emitter (server or browser)
*
*
* - pure javascript - server compatible, browser compatible
* - dont rely on the browser doms
* - super simple - you get it immediatly, no mistery, no magic involved
Expand All @@ -9,42 +9,47 @@
* - make it safer to use
*/

var MicroEvent = function(){}
MicroEvent.prototype = {
bind : function(event, fct){
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
},
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))
}
}
var MicroEvent = function(){}
MicroEvent.prototype = {
bind : function(event, fct){
this._events = this._events || {};
this._events[event] = this._events[event] || [];
this._events[event].push(fct);
},
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))
}
}
};

// Add some method aliases.
MicroEvent.prototype.on = MicroEvent.prototype.bind;
MicroEvent.prototype.off = MicroEvent.prototype.unbind;
MicroEvent.prototype.emit = MicroEvent.prototype.trigger;

/**
* 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', 'unbind', 'trigger'];
for(var i = 0; i < props.length; i ++){
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
}
MicroEvent.mixin = function(destObject){
var props = ['bind', 'unbind', 'trigger', 'on', 'off', 'emit'];
for(var i = 0; i < props.length; i ++){
destObject.prototype[props[i]] = MicroEvent.prototype[props[i]];
}
}

// export in common js
if( typeof module !== "undefined" && ('exports' in module)){
module.exports = MicroEvent
module.exports = MicroEvent
}