tiny-emitter
tiny-emitter copied to clipboard
Check whether callback is actually a function
I ran into a problem where I got an error message like TypeError: Cannot read properties of undefined (reading 'apply')
in E.emit
. This was due to a code change where I changed the name of an event handler but forgot to change it also in the call to emitter.on()
.
It took me quite some time to find the problem in the code as it is not obvious from the error message which event handler (call to on()
) caused the problem.
It would be great if the emitter would check in the on()
and once()
methods whether callback is actually a function and if not throw an error. This way it would directly indicate which portion of the code was trying to register a non-callable event handler. Something like:
if (typeof callback !== 'function') throw new Error('Callback is not a function');
The issue is easy to reproduce:
emitter.on('some-event', undefined);
emitter.emit('some-event');
emitter.on('some-event', 'string');
emitter.emit('some-event');