@massive/eventemitter-ts
v1.1.1
Published
```typescript import { EventEmitter } from 'eventemitter-ts';
Downloads
63
Readme
Classic EventEmitter for TypeScript
import { EventEmitter } from 'eventemitter-ts';
type Shifts = 'R' | 'N' | 1 | 2 | 3 | 5 | 6
/// Define event map
export interface ErrorEvent extends Error {}
interface CarBaseEvent<T> {
readonly car: Car;
readonly data: T;
}
export interface FuelLevel extends CarBaseEvent<number> {}
export interface TransmissionChange extends CarBaseEvent<Shifts> {}
export interface CarEventMap {
error: ErrorEvent;
fuel: FuelLevel;
shift: TransmissionChange;
}
/// Extend target class
class Car extends EventEmitter<CarEventMap> {
private fuel: number = 0
public goto(loc: string){
if (this.fuel <= 0) {
this.emit('error', new Error('Not enough fuel!'))
}
}
public refuel(data: number) {
this.fuel = data
this.emit('fuel', {car: this, data})
}
public shift(data: Shifts) {
this.emit('shift', {car: this, data: 1})
}
public destroy(){
this.off()
}
}
/// Add listener
const car = new Car()
car.on('shift', (event) => {
console.log(`👋 shift -> ${event.data}`)
})
car.shift('R')