@pyramine/events
v2.0.0
Published
## Installation
Downloads
2
Readme
Events
Installation
npm install @pyramine/events
Usage
First we need to define the "event-map". Therefore, we create a new interface, which keys define the event names. The value of the interface defines the arguments for a specific event.
Example:
interface MyEventMap extends EventMap {
click: [name: string];
change: [index: number, color: string];
}
Here we define two events: click
and change
. The click
event expects one argument, a name
of type string
. The second event change
expects two arguments, an index
of type number
and a color
of type string
.
You can specify as many events as you like. Also, the arguments you define for an event is completely up to you.
Emit events
Now, if you want to dispatch/emit an event you can do it as follows:
import {EventHub} from "@pyramine/events";
const eventHub = new EventHub<MyEventMap>();
eventHub.emit('click', 'my-name');
eventHub.emit('change', 1, 'red');
Listen for Events
import {EventHub} from "@pyramine/events";
const eventHub = new EventHub<MyEventMap>();
eventHub.on('click', (name) => {
console.log(name);
});
eventHub.on('change', (index, color) => {
console.log(index, color);
});
// Listening only once
eventHub.once('click', (name) => {
console.log(name);
});
Stop Listening:
eventHub.off('click', callback);