此文章内容兼容API12,使用harmony next应用开发
Emitter 对标 Eventbus,实现同进程同线程、同进程跨线程通信
基本使用
1,发送数据
//1
emitter.emit({
eventId: eventId, // eventId -> number 类型
priority: emitter.EventPriority.HIGH
}, {
data: xxx // { string:any }
});
//2
emitter.emit('id')
//3
emitter.emit('id',{
data: {
"content": data,
}
})
2,监听
public static listen(eventId: number, callback:Callback<emitter.EventData>) {
emitter.on({ eventId: eventId }, callback)
}
3,取消监听
- 一般在 aboutToDisappear 处调用
- 注销时,eventid与回调对象需配对,否则回调注销失败
emitter.off(eventId);
属性
1,优先级
IMMEDIATE 0 表示事件被立即投递。
HIGH 1 表示事件先于LOW优先级投递。
LOW 2 表示事件优于IDLE优先级投递,事件的默认优先级是LOW。
IDLE 3 表示在没有其他事件的情况下,才投递该事件。
2,传递的数据 data,类型是 { [key: string]: any }
3,重复注册
- eventId一样,且关联的回调对象为同一个,则只会在第一次注册的回调对象生效
- eventId一样,且关联的回调对象不同,则多个回调对象均生效,根据注册顺序决定回调顺序
方法
1,单词订阅事件,执行完回调函数后,自动取消订阅
public static listenOnce(eventId: number, callback:Callback<emitter.EventData>) {
emitter.once({ eventId: eventId }, callback)
}