Question

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.

Was it helpful?

Solution

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

OTHER TIPS

You are looking for Observer Pattern for JavaScript.

Spine and Backbone have some nice implementations for observers.

But a new nice pattern is the Promises pattern that are documented at CommonJS

jQuery 1.7 have implemented and is deeply using the promise pattern.

My favorite implementation from Promises pattern is the Q from @kriskowal

I hope, that this sources help you in your quest.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top