Typescript event emitter.
使用typescript实现的事件收发机制.
npm install @viscum/event --save
Global emitter & handlers.
import { Event, on, emit } from '@viscum/event'
// Define event class
class FoobarEvent extends Event('foobar') {
foo: string = 'foo'
bar: string = 'bar'
}
// Add handler.
const off = on(FoobarEvent, (evt: FoobarEvent, from?: Emitter) => {
console.log(`${evt.foo} - ${evt.bar} - ${from ? from.name : 'nobody'}`)
})
class Emitter { name: 'emitter' }
const emitter = new Emitter()
// Emit event.
emit(new FoobarEvent) //=> print 'foo - bar - nobody'
// Emit event from an emitter.
emit(new FoobarEvent, emitter) //=> print 'foo - bar - emitter'
// Remove handler.
off()
HasEventEmitter mixin.
import mix from 'mix-with'
import { HasEventEmitter } from 'mix-with'
class MyEvent extends Event('my') {}
class Base {}
class Foobar extends mix(Base).with(HasEventEmitter) {
name: string = 'foobar'
action () : void {
// Emit event from this.
this.emit(new MyEvent())
}
}
const foobar = new Foobar()
// Add handler.
on(MyEvent, (evt: MyEvent, from: Foobar) => {
console.log(from.name)
})
foobar.action() //=> print 'foobar'