EventDispatcher
This is a tiny JavaScript library for implementing an event dispatcher(emitter) with easy.
Written by TypeScript which gives you the power of type checking as well 💖.
Installation
Install the package via npm
npm i EventDispatcher
Basic Usage
import { EventDispatcher } from 'EventDispatcher';
const myEventTypes = ['click', 'move', 'touch'];
const ed = new EventDispatcher({ validEventTypes: myEventTypes });
ed.on('click', function (event) {
console.log(event.type);
});
const touchEventHandler = () => {
console.log('touched!');
};
ed.one('touch', touchEventHandler);
const eventObject = {
'arg1': 'foo',
'arg2': 'bar'
};
ed.trigger('click', eventObject);
ed.trigger('touch');
ed.off('click');
ed.off('touch', touchEventHandler);
ed.disable().trigger('click');
ed.enable().trigger('click');
ed.on('foo',() => {})
ed.off('foo')
ed.trigger('foo')
"unbind" event handler
There is a special way to remove event listener, which can be used in some special design patterns.
const eventHandler = () => {}
const off = ed.on('foo', eventHandler)
off()
Catch previous triggered event
You can catch the previous already triggered event by passing a third option parameter to the on
method.
const mouseEvent = new MouseEvent('click')
ed.trigger('click', mouseEvent)
ed.on('click', clickEventHandler, { triggerLastEvent: true })
Use it as a mixin
You can mixin the APIs into another class by extending the API class.
class Foo extends ed.Api() {
}
const foo = new Foo;
foo.trigger('click');
If you have a base class already, I would recommend you to use ts-mixer to make it possible.
In that case your code would be:
import { Mixin } from 'ts-mixer';
class Foo extends Mixin(BaseClass,ed.Api()) {
}
const foo = new Foo;
foo.trigger('click');
TypeScript
Leverage TypeScript for strict typing and compilation by giving an event interface.
import {EventDispatcher, Event} from 'EventDispatcher';
interface Events {
click(event: MouseEvent): void
touch(event: Event): boolean
}
class MouseEvent extends Event {
public timeStamp: number
constructor(type: string) {
super(type);
this.timeStamp = (new Date).getTime();
}
}
const ed = new EventDispatcher<Events>({ validEventTypes: ['click', 'touch'] });
ed.on('foo',() => {})
ed.off('foo',() => {})
ed.trigger('foo')
ed.on('click',() => {})
ed.off('click',() => {})
ed.trigger('click')
ed.on('touch',() => 10)
ed.on('touch',() => true)
ed.trigger('touch',10)
ed.trigger('touch',{foo:'bar'})
ed.trigger(new MouseEvent('click'))
API
For more information just take a look at the test file.