简体   繁体   中英

javascript add Single Event Lister for multiple events like ajax function callbacks succss, fail etc

I want to crate javascript object that accepts setting and provide multiple events with single addListener function. for example addListener({success: callback,fail:callback}) etc. I hope my requirement is clear.

var myCustomObject=new MyCustomeObject({name:'anu', age:'30'});

myCustomObject.addListener({

success: function(e){ console.log(e)},
fail: function(ef){ console.log(ef)}

});

You can implement your own EventEmitter like this:

const EventEmitter = function () {
    this.events = {};
};

Then you need to create function for subscribe:

EventEmitter.prototype.on = function (event, listener) {
if (typeof this.events[event] !== 'object') {
    this.events[event] = [];
}

this.events[event].push(listener);
};

and of course function for emit:

EventEmitter.prototype.emit = function (event) {
let i, listeners, length, args = [].slice.call(arguments, 1);

if (typeof this.events[event] === 'object') {
    listeners = this.events[event].slice();
    length = listeners.length;

    for (i = 0; i < length; i++) {
        listeners[i].apply(this, args);
    }
}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM