HarmonyOS鸿蒙Next中关于emitter的使用问题

HarmonyOS鸿蒙Next中关于emitter的使用问题

我目前代码中有一个使用场景,我写一个简单的demo展示一下:

export class BaseA{
  constructor() {
    this.registerNotification()
  }
  registerNotification() {
  }
}

//一个子类

import { LogUtil, NotificationUtil } from "login_lpm";
import { BaseA } from "./BaseA";
import { emitter } from "@kit.BasicServicesKit";

export class ChildB extends BaseA {
  constructor() {
    super()
    ///这里就可以订阅成功,收到消息回调
    emitter.on(this, "123123", this.callback)
  }
  registerNotification(): void {
    ///重写父类的registerNotification方法订阅,就无法收到消息回调
    // emitter.on("123123", this.callback)
  }

  callback = () => {
    LogUtil.info(`aaaaa  这是一个测试回调`)
  }

  unRegisterNotification():void{
    emitter.off("123123", this.callback)
  }
}

//page

@Component
export struct TestPage {
  build() {
    Scroll() {
        Button('测试emitter之订阅')
          .onClick(() => {
            // emitter.on({ eventId: 123123, }, this.callback)
            // NotificationUtil.on(this, "123123", this.callback)
            const childB = new ChildB()
          })
        Button('测试emitter之发送消息')
          .onClick(() => {
            emitter.emit("123123")
          })
        Button('测试emitter之解绑消息')
          .onClick(() => {
            // NotificationUtil.off(this, "123123", this.callback)
          })
      }
    }
}

我在childB中的构造方法里面emitter.on就可以订阅成功,但是在重写BaseA中的registerNotification方法中emitter.on就收不到订阅消息。我怀疑是this指针的问题,但是我没有证据,有没有人说说为什么?

更多关于HarmonyOS鸿蒙Next中关于emitter的使用问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中,emitter用于事件发布与订阅。通过EventEmitter类,开发者可以创建事件发射器,使用on方法订阅事件,emit方法发布事件。事件名称需唯一,支持传递参数。off方法用于取消订阅。emitter适用于组件间通信,解耦业务逻辑。

更多关于HarmonyOS鸿蒙Next中关于emitter的使用问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


从代码来看,这确实是典型的this绑定问题。在HarmonyOS Next中,emitter.on()的上下文绑定很关键。

分析原因:

  1. constructor中调用emitter.on()时,this指向ChildB实例,回调函数能正确绑定。
  2. registerNotification方法中,如果直接使用emitter.on("123123", this.callback),回调函数的this会丢失绑定。

解决方案:

  1. 使用箭头函数定义callback(您已正确使用)。
  2. registerNotification中调用时也需要绑定this
registerNotification() {
  emitter.on("123123", this.callback.bind(this))
  // 或保持与constructor一致写法
  emitter.on(this, "123123", this.callback)
}

根本原因是JS/TS的方法调用时的this绑定规则,在继承体系中需要特别注意方法调用的上下文。建议统一使用箭头函数或显式绑定来避免这类问题。

回到顶部