Simple and light-weight event emitter library for JavaScript.
- No dependencies, less than 1KB pure JavaScript implementation.
onmethod returns anID. Use thisIDto remove specific listener or theevent-nameto remove all the listeners.- No aliases, just
emit,onandoffmethods.
const emitter = new NJEvents();
const id = emitter.on('hey', data => {
console.log(data);
});
emitter.emit('hey', 'how are you?');
emitter.off(id); npm install --save nj-events
You can use NJEvents as an ES6 module as follows:
import NJEvents from 'nj-events';
const emitter = new NJEvents();Alertnatively you can include the script.js script before the closing </body> tag and then in your JS create a new instance of NJEvents as below.
<script src="path/to/script.js"></script>
<script>
const emitter = new NJEvents();
</script>NJ-Events are driven by the on, emit, off methods which are detailed below.
on()- the listener is registered and will be active until removed explicitly.once()- the listener is removed after first trigger.- both methods take an
event_name:string,callback:functionand an optionalid:stringas parameters.
const emitter = new NJEvents();
const id_on = emitter.on('hey', data => { // listener is registered until removed
console.log(data);
});
const id_once = emitter.once('hey', data => { // listener is removed after first trigger
console.log(data);
});
const custom_id = emitter.on('hey', data => { // init with custom id
console.log(data);
}, YOUR_CUSTOM_ID);An event is triggered using the emit() by passing the event_name:string and data:any
emitter.emit('hey', 'how are you?');An event can be unregistered using the off() with the below parameters
event_name- any matching events and its listeners will be removed.id- event with the particular id will be removed, the event would still exist.
emitter.off('hey'); // unregister using event-name
emitter.off(id); // unregister using the event IDCheck out the Releases and Change Logs for more information.