EventCycle
Simple and flexsible event trigger, Written by TypeScript.
- 💪 All case in test cover
Install
npm i event-cycle
Usage
Simply initialize by Singleton Pattern:
// eventCycle.ts
import EventCycle from 'event-cycle';
export default new EventCycle();
Then use it in any function:
import eventCycle from './eventCycle';
// somewhere to subscribe event
eventCycle.on('hello', (data: string) => console.log(`hello ${data || 'world'}`));
// somewhere to publish event
eventCycle.emit('hello'); // print 'hello world'
eventCycle.emit('hello', 'vv13'); // print 'hello vv13'
Api
on(type, handler)
- arguments
type: string
, subscriber event name, allow duplicatehandler: (data?: any) => void
, event subscription callback, accept a data byemit
onAll(handler)
- arguments
handler: (type: string, data?: any) => void
, every event publisher will trigger this callback, it receive event type and data byemit
once(type, handler)
- arguments
type: string
, subscriber event name, only trigger once, after that it will auto-cancel subscribehandler: (data?: any) => void
, event subscription callback, accept a data byemit
emit(type, data)
- arguments
type: string
, publisher event name, it will be trigger subscription callbackdata: any
, event data can be used by subscription callback
off(type, handler)
- arguments
type: string
, event name who will be removedhandler?: (event?: any) => void;
, specific removing function, if it's not provided,off
will default remove all subscriber in such type.
offAll(handler)
- arguments
handler?: (event?: any) => void;
, remove the handler from global subscriber, if handler not provided,offAll
will remove all subscriber.