Last active
August 29, 2015 14:10
-
-
Save leaysgur/3ab8416ce41883ae1ccd to your computer and use it in GitHub Desktop.
SimpleEventInterface
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 Eve = function() { | |
this._events = {}; | |
}; | |
Eve.prototype = { | |
constructor: Eve, | |
on: function(evName, handler) { | |
var events = this._events; | |
if (!(evName in events)) { | |
events[evName] = []; | |
} | |
events[evName].push(handler); | |
}, | |
off: function(evName, handler) { | |
var events = this._events; | |
if (!(evName in events)) { | |
return; | |
} | |
if (!handler) { | |
events[evName] = []; | |
} | |
var handlerIdx = events[evName].indexOf(handler); | |
if (handlerIdx >= 0) { | |
events[evName].splice(handlerIdx, 1); | |
} | |
}, | |
trigger: function(evName, evData) { | |
var events = this._events, | |
handler; | |
if (!(evName in events)) { return; } | |
var i = 0, l = events[evName].length; | |
for (; i < l; i++) { | |
handler = events[evName][i]; | |
handler.handleEvent ? handler.handleEvent.call(this, evData) | |
: handler.call(this, evData); | |
} | |
} | |
}; |
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
// instance | |
var e = new Eve(); | |
// handlers | |
var sayFoo = function(data) { console.log('foo!', data); }; | |
var sayHoo = function(data) { console.log('hoo!', data); }; | |
var sayWoo = { handleEvent: function(data) { console.log('woo!', data); } }; | |
// listen | |
e.on('foo', sayHoo); | |
e.on('foo', sayFoo); | |
e.on('foo', sayWoo); | |
// call both two handlres | |
e.trigger('foo', 'bar'); | |
// remove one | |
e.off('foo', sayFoo); | |
// call only one | |
e.trigger('foo', 'bar2'); | |
// remove all | |
e.off('foo'); | |
// no one called | |
e.trigger('foo', 'bar3'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment