So this should be relatively simple. In fact it should be super trivial. But I am blanking on how to handle this, consider the following method on a class:
trigger(name, ...args) {
let returnValue = null;
if (!this.events.length > 0) {
throw Error('There are no registered events.');
}
this.events.forEach((event) => {
console.log(event.name, name)
if (event.name === name) {
if (args !== undefined) {
returnValue = event.cb(...args, this);
} else {
returnValue = event.cb(this);
}
} else {
throw Error('could not find ' + name + ' in the list of registered events.');
}
});
return returnValue;
}
Straight forward and simple. Heres the error:
console.log src/events/handler.js:51 event.with.params event.with.params
console.log src/events/handler.js:51 event.with.no.params event.with.params
It errors out if you have multiple events registered. I thought the easiest fix wad to do a return; once the name matches, as you can see it does match once. Heres the test:
test('success in triggering multiple events', () => {
eventHandler.register('event.with.params', (a, b) => {
return a + ' ' + b;
});
eventHandler.register('event.with.no.params', () => {
return 'no params'
});
expect(eventHandler.trigger('event.with.params', 'a', 'b')).toEqual('a b');
expect(eventHandler.trigger('event.with.no.params')).toEqual('no params');
});
Here you can see we register two events, then we attempt to trigger both of them. The error in the test is:
could not find event.with.params in the list of registered events.
at Error (native)
Accept by console.log it did find it ... Then it continued on.
I know this is trivial to fix but I cant seem to figure it out. help ??
...args, it will never be undefined unless your function was called astrigger(someName, undefined)- iftrigger(someName)is called,argswill be[]. On a similar note,callback(...[], this)is the same ascallback(this).returnValueif multiple handler are registered for this event? At the moment you'll overwritereturnValueand return the value from the last callback called.eventsdoes not match the name- if there are any events registered with a different name, thanks @Thomasargswill never be falsy. Even if called astrigger(someName, undefined)args will be[undefined]