HarmonyOS emitter.on回调里接收的数据为空?

emitter.emit时传递map数据,在emitter.on回调里接收的map是空的。

import { emitter } from '@kit.BasicServicesKit';

@Entry
@Component
struct EmitterTest {
  aboutToAppear(): void {
    emitter.on("EmitterTest", (eventData: emitter.EventData) => {
      console.info('EmitterTest callback, eventData:' + eventData["1"]);
      console.info('EmitterTest callback, eventData:' + eventData["2"]);
    });
  }

  build() {
    RelativeContainer() {
      Button('sned emitter', { stateEffect: true, type: ButtonType.Capsule })
        .width('80%')
        .height(40)
        .margin(10)
        .onClick(() => {
          let eventDataMap = new Map<string, Object>()
          eventDataMap.set("1", "111")
          eventDataMap.set("2", "222")
          let eventData: emitter.EventData = {
            data: { eventDataMap }
          };
          let options: emitter.Options = {
            priority: emitter.EventPriority.HIGH
          };

          emitter.emit("EmitterTest", options, eventData);
        })
    }
    .height('100%')
    .width('100%')
  }
}
阅读 465
1 个回答

参考示例:

import { emitter } from '@kit.BasicServicesKit';

@Entry
@Component
struct EmitterTest {
  aboutToAppear(): void {
    emitter.on("EmitterTest", (eventData: emitter.EventData) => {
      let eventDataMap = eventData.data?.eventDataMap as Map<string, Object>
      console.info('EmitterTest callback, eventData:' + eventDataMap.get('1'));
      console.info('EmitterTest callback, eventData:' + eventDataMap.get('2'));
    });
  }

  build() {
    RelativeContainer() {
      Button('sned emitter', { stateEffect: true, type: ButtonType.Capsule })
        .width('80%')
        .height(40)
        .margin(10)
        .onClick(() => {
          let eventDataMap = new Map<string, Object>()
          eventDataMap.set("1", "111")
          eventDataMap.set("2", "222")
          let eventData: emitter.EventData = {
            data: { eventDataMap }
          };
          let options: emitter.Options = {
            priority: emitter.EventPriority.LOW
          };

          emitter.emit("EmitterTest", options, eventData);
        })
    }
    .height('100%')
    .width('100%')
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏