HarmonyOS 事件回调

有两个页面,A、B,在A中通过router.pushUrl方法跳转至B页面。B页面有一个按钮btn,点击btn时,如何将btn的触发事件告知A页面。B页面从始至终不进行back(返回)。

HarmonyOS
2024-12-20 15:19:23
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
put_get

使用自定义订阅事件的方式来实现该功能:参考demo:

//index.ets
import display from '@ohos.display';
import emitter from '@ohos.events.emitter';
import { router } from '@kit.ArkUI';
import { JSON } from '@kit.ArkTS';

@Entry
@Component
struct DisplayTest {

  build() {
    Column({space:20}){
      Button('Test')
        .type(ButtonType.Capsule)
        .onClick(() => {
          let innerEvent: emitter.InnerEvent = {
            eventId: 12222
          };
          //触发id为12222的事件
          emitter.on(innerEvent, (data) => {
            console.info('once callback' + JSON.stringify(data));
          });
          router.pushUrl({
            url:'pages/PageOne'
          })
        })
        .width('50%')
    }
    .width("100%")
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

//PageOne.ets
import emitter from '@ohos.events.emitter';

@Entry
@Component
struct PageOne {



  build() {
    Column(){
      Text('PageOne')
        .width('50%')
      Button('send')
        .type(ButtonType.Capsule)
        .width('50%')
        .onClick(() => {
          let eventData: emitter.EventData = {
            data: {
              "content": "c",
              "id": 1,
            }
          };

          let innerEvent: emitter.InnerEvent = {
            eventId: 12222,
            priority: emitter.EventPriority.HIGH
          };
          //发布id为12222的事件
          emitter.emit(innerEvent, eventData);
        })
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.

参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-emitter-V5#emitteremit

分享
微博
QQ
微信
回复
2024-12-20 18:27:50
相关问题
HarmonyOS 点击事件方法
1067浏览 • 1回复 待解决
HarmonyOS Scroll组件事件问题
1008浏览 • 1回复 待解决
焦点事件onBlur/onFocus无法触发
2900浏览 • 1回复 待解决
HarmonyOS Watch没有
831浏览 • 1回复 待解决