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.
I have a small
EventEmitterI 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