I write lots of little libraries and modules and usually these libraries and modules have have some events associated with them. Until now I've been writing these like (shortened down a lot):
Library.prototype.on = function(event, callback){
self = this;
self.events[event] = callback;
}
then a user would do something such as:
Library.on('foo',function(){
console.log('bar');
});
Is there a better more performant way to do this though or is this a standard way of implementing this? I want a simple API that i can drop into any JS project to support this behavior.
var EventEmitter = {
constructor: function _constructor() {
this._events = [];
return this;
},
on: function _on(ev, handler) {
if (!this._events[ev]) {
this._events[ev] = [];
}
this._events[ev].push(handler);
},
removeListener: function _removeListener(ev, handler) {
if (!this._events[ev]) return;
this._events[ev].splice(this._events[ev].indexOf(handler), 1);
},
removeAll: function _removeAll(ev) {
delete this._events[ev];
},
emit: function _emit(ev, data) {
if (!this._events[ev]) return;
this._events[ev].forEach(invokeHandler);
function invokeHandler(handler) {
handler(data);
}
}
};
I have a small EventEmitter
I use when I need quick and dirty custom events.
The only difference between mine and your implementation is that mine allows multiple callbacks per event.
For anything serious I use an event library like EventEmitter2