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

问题现象

应该如何实现事件只在一个UIAbility实例中订阅和触发

阅读 329
1 个回答

解决措施

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

代码示例:

import { UIAbility } from '@kit.AbilityKit'; 
 export default class EntryAbility extends UIAbility { 
    onForeground() { 
        this.context.eventHub.on('myEvent', this.eventFunc); 
        // 结果: 
        // eventFunc is called,undefined,undefined 
        this.context.eventHub.emit('myEvent'); 
        // 结果: 
        // eventFunc is called,1,undefined 
        this.context.eventHub.emit('myEvent', 1); 
        // 结果: 
        // eventFunc is called,1,2 
        this.context.eventHub.emit('myEvent', 1, 2); 
    } 
     eventFunc(argOne:number, argTwo:number) { 
        console.log('eventFunc is called, ${argOne}, ${argTwo}'); 
    } 
}

参考链接

使用EventHub进行数据同步

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进