简体   繁体   中英

JS How to check if callback is exist?

I have array of registered callbacks

this.events[eventName].push({callback: callback});

The problem is that, than after user actions in array can be added the same calback, which already exists.

How to check that callback is exist?

What will be happening, if two same callbacks will be registered from two several places of code? It is logical that they should be executed. The question is, how not to re-register a callback call from the same place.

A data structure that is suitable for this, is the ES6 Map . If you use that instead of an array, it will automatically only store uniques:

this.events = new Map(); // one time initialisation instead of `this.events = []`;
// ...
this.events[eventName].set(callback, {callback: callback});

And execute the callbacks for an event as follows:

this.events[eventName].forEach(({callback}) => callback());

If the callback is the only thing you store, then you could use a Set instead:

this.events = new Set();
// ...
this.events[eventName].add(callback);

And execute the callbacks for an event as follows:

this.events[eventName].forEach(callback => callback());

You can use Array.prototype.some() to test if the callback already exists:

if (!this.events[eventName].some(function(el) {
    return el.callback == callback;
}) {
    this.events[eventName].push({callback: callback});
}

With a simple loop?

for (var i = 0; i < this.events[eventName].length; i++)
  if (this.events[eventName].callback === callback)
    return;    // already exists, so return without pushing

this.events[eventName].push({callback: callback});

You can use Array.prototype.some function to check if callback exists

 class Observer { constructor(){ this.events = {}; } on(name, callback){ if(typeof name !== 'string' || typeof callback !== 'function') return this; let ary = this.events[name] || (this.events[name] = []); if(ary.some(obj => obj.callback === callback)) return this; ary.push({callback}); return this; } } let observer = new Observer(); function testHandler(){} observer.on('test', testHandler) .on('test', testHandler); console.log(observer.events); 

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