simple-eventer
v2.1.1
Published
Simple events interface
Downloads
7
Maintainers
Readme
simple-eventer
Simple events interface for es6/babel classes.
installation
Install from npm:
$ npm install simple-eventer
usage
Use it as base class for your module.
import SimpleEventer from 'simple-eventer';
class Example extends SimpleEventer {
constructor() {
super();
this.seconds = 0;
setInterval(() => {
this.seconds += 1;
// Fire your event
this.fire('onesecond', this.seconds);
}, 1000);
}
}
Bind events to your module.
// Bind your event
(new Example()).on('onesecond', (event) => {
console.log(`Type: ${event.type}, Target/Data: ${event.target}`);
});
// Type: onesecond, Target/Data: 1
// Type: onesecond, Target/Data: 2
// Type: onesecond, Target/Data: 3
Or use events globally
let seconds = 0;
setInterval(() => {
seconds += 1;
// Fire your event
SimpleEventer.fire('onesecondGlobal', seconds);
}, 1000);
// Bind your event
SimpleEventer.on('onesecondGlobal', (event) => {
console.log(`Type: ${event.type}, Target/Data: ${event.target}`);
});
// Type: onesecondGlobal, Target/Data: 1
// Type: onesecondGlobal, Target/Data: 2
// Type: onesecondGlobal, Target/Data: 3
methods
Three methods are available.
fire(type, [target])
Emmiting event of inheriting module with provided type. Target becomes this if not specified.
// Called inside your module where this is the module instance
this.fire('eventtype', this.target);
// Called on your module instance - like trigger in jQuery
module.fire('eventtype', module.target);
on(type, listener)
Registers listener for event of provided type.
function listener(event) {
console.log(event.type);
// eventtype
console.log(event.target);
// module.target
}
module.on('eventtype', listener);
off(type, listener)
Removes listener for event of provided type.
module.off('eventtype', listener);