Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most performant way to write custom .on()/.bind() JavaScript

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.

like image 1000
Oscar Godson Avatar asked Nov 27 '25 15:11

Oscar Godson


1 Answers

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

like image 82
Raynos Avatar answered Nov 29 '25 05:11

Raynos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!