@eggjs/eventbus-decorator
使用量
发射事件
import { EventBus } from '@eggjs/eventbus-decorator';
// Define event first.
// Ts can check event and args type for you.
declare module '@eggjs/eventbus-decorator' {
interface Events {
hello: (msg: string) => Promise<void>;
}
}
class Foo {
@Inject()
private readonly eventBus: EventBus;
bar() {
this.eventBus.emit('hello', '01');
}
}
软体事件
在记忆中缓存事件直到解锁.
class Foo {
@Inject()
private readonly eventBus: ContextEventBus;
bar() {
this.eventBus.cork();
// ...do something
this.eventBus.emit('hello', '01');
// ...do other things
// emit all cached events
this.eventBus.uncork();
}
}
处理事件
@Event('hello')
export class Foo {
async handle(msg: string): Promise<void> {
console.log('msg: ', msg);
}
}
处理多个事件
@Event('hello')
@Event('hi')
export class Foo {
async handle(msg: string): Promise<void> {
console.log('msg: ', msg);
}
}
插入事件上下文
如果您想知道正在处理哪个事件,请输入事件上下文. 上下文参数必须是第一个参数
@Event('hello')
@Event('hi')
export class Foo {
async handle(@EventContext() ctx: IEventContext, msg: string): Promise<void> {
console.log('eventName: ', ctx.eventName);
console.log('msg: ', msg);
}
}