文档管理中心

如何让事件只在一个UIAbility实例中传递

本文导读

在UIAbility中使用EventHub订阅事件,EventHub模块提供了事件中心,订阅、取消订阅、触发事件的能力。

参考代码如下:

收起
自动换行
深色代码主题
复制
  1. import { UIAbility } from '@kit.AbilityKit';
  2. export default class EntryAbility extends UIAbility {
  3. onForeground() {
  4. this.context.eventHub.on('myEvent', this.eventFunc);
  5. // result:
  6. // eventFunc is called,undefined,undefined
  7. this.context.eventHub.emit('myEvent');
  8. // result:
  9. // eventFunc is called,1,undefined
  10. this.context.eventHub.emit('myEvent', 1);
  11. // result:
  12. // eventFunc is called,1,2
  13. this.context.eventHub.emit('myEvent', 1, 2);
  14. }
  15. eventFunc(argOne: number, argTwo: number) {
  16. console.log(`eventFunc is called, ${argOne}, ${argTwo}`);
  17. }
  18. }