Javascript Domless events

Using jQuery or nodejs makes you addicted to pubsub (publish/subscribe) model.
Nodejs has nattive support for event emitters but javascript doesn’t have. Events are only binded to a DOM, using which doesn’t make sense and its also adds to performance cost.

To solve the problem i wrote a custom class which implements `on` and `emit` method, Yes some methods like `once` are missing.

var tikEvent = function () {
    this.listeners = {};

};
tikEvent.prototype.on = function (event, callback) {
    if (!this.listeners.hasOwnProperty(event)) {
        this.listeners[event] = [];
    }
    this.listeners[event].push(callback);
};

tikEvent.prototype.emit = function (event) {
    if (this.listeners.hasOwnProperty(event)) {
        var args = Array.prototype.slice.call(arguments);
        args.shift();

        for (var i = 0; i < this.listeners[event].length; ++i) {
            try {
                this.listeners[event][i].apply(null, args);
            } catch (e) {
               console.error(e);
            }
        }
    }
};


//Some test code.

vat test = new tikEvent();
test.on('emitted',function(d){

console.log(d);
}

test.emit('emitted',"test");

Leave a Reply

Your email address will not be published.