在UIAbility中使用EventHub订阅事件,EventHub模块提供了事件中心,订阅、取消订阅、触发事件的能力。
参考代码如下:
- import { UIAbility } from '@kit.AbilityKit';
-
- export default class EntryAbility extends UIAbility {
- onForeground() {
- this.context.eventHub.on('myEvent', this.eventFunc);
- // result:
- // eventFunc is called,undefined,undefined
- this.context.eventHub.emit('myEvent');
- // result:
- // eventFunc is called,1,undefined
- this.context.eventHub.emit('myEvent', 1);
- // result:
- // eventFunc is called,1,2
- this.context.eventHub.emit('myEvent', 1, 2);
- }
-
- eventFunc(argOne: number, argTwo: number) {
- console.log(`eventFunc is called, ${argOne}, ${argTwo}`);
- }
- }