Custom, simple, extendable event/messaging system written in ES6
From the root of your project.
npm install es6-event-emitter --save
Simple implementation of emitter. See api below.
import Emitter from 'es6-event-emitter';
export default class Component extends Emitter {
constructor(){
super();
}
//-- Trigger
someAction(){
...
this.trigger('component:action');
}
//-- Trigger with data
someOtherAction(){
...
this.trigger('component:otheraction', {
foo: 'bar',
baz: 'buzz'
});
}
}
//-- Create a new component
const component = new Component();
//-- Set up functions for listeners - best practice in case you want to remove them later.
const action = () => {
console.log('action triggered');
}
const otheraction = data => {
console.log(`other action triggered with data ${data}`);
}
//-- Register listeners
component.on('component:action', action);
component.on('component:otheraction', otheraction);
//-- Call methods
component.someAction();
component.someOtherAction();
Registers a listener
component.on('component:action', action);
Removes a registered listener from the event stack
component.off('component:action', action);
Registers a listener that will only fire once no matter how many times you try to trigger
component.once('component:action', action);
Triggers a registered event with optional data
this.trigger('component:action');
//-- With data
this.trigger('component:action', {
foo: 'bar',
baz: 'buzz'
});
Destroys the entire event emitter
component.destroy();
View the test coverage
npm test