HarmonyOS eventHub注册和移除事件监听

eventHub在注册事件后,如果将eventHub封装成单例调用,on函数里面参照官方demo的Function写方法名就无法回调,必须写成()=>{}这种形式才能调用,eventHub封装如下:

export class EventBus {
  private eventHub: common.EventHub = (getContext(this) as common.UIAbilityContext).eventHub;
  private static instance: EventBus;

  private constructor() {
  }

  public static getInstance(): EventBus {
    if (!EventBus.instance) {
      EventBus.instance = new EventBus();
    }
    return EventBus.instance;
  }

  postEvent(eventKey: string, ...args: Object[]) {
    this.eventHub.emit(eventKey, ...args);
  }

  on(eventKey: string, callback: Function) {
    this.eventHub.on(eventKey, callback)
  }

  off(eventKey: string, callback?: Function) {
    this.eventHub.off(eventKey, callback)
  }
}
//这种能生效
EventBus.getInstance().on("test",()=>{})

//这种不生效,notifyUI就是一个普通函数notifyUI(){}
EventBus.getInstance().on("test", this.notifyUI)
HarmonyOS
2024-12-25 11:56:12
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Heiang

this指向问题

目前规避方案可以使用bind(this),但是官方不推荐使用bind方式,推荐的是箭头函数

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/typescript-to-arkts-migration-guide-V5#%E4%B8%8D%E6%94%AF%E6%8C%81functionbind

分享
微博
QQ
微信
回复
2024-12-25 14:17:52
相关问题
注册监听关机事件,该如何处理?
1109浏览 • 1回复 待解决
系统监听注册的onoff的用法问题
2180浏览 • 1回复 待解决
HarmonyOS 接收不到eventhub事件
191浏览 • 1回复 待解决
HarmonyOS ArkTS注册Native C函数监听
500浏览 • 1回复 待解决
怎么监听键盘的弹起关闭事件
3021浏览 • 1回复 待解决
HarmonyOS 键盘事件监听问题
971浏览 • 1回复 待解决
HarmonyOS 点击事件监听问题
310浏览 • 1回复 待解决
HarmonyOS eventHub创建方式咨询
301浏览 • 1回复 待解决