EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件的能力。
NOTE
本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
本模块接口仅可在Stage模型下使用。
使用说明
在使用eventHub的功能前,需要通过Ability实例的成员变量context获取。
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
func1(){
console.log('func1 is called');
}
onForeground() {
this.context.eventHub.on('123', this.func1);
}
}
EventHub.on
on(event: string, callback: Function): void;
订阅指定事件。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:

示例:
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
onForeground() {
this.context.eventHub.on('123', this.func1);
this.context.eventHub.on('123', () => {
console.log('call anonymous func 1');
});
// 结果:
// func1 is called
// call anonymous func 1
this.context.eventHub.emit('123');
}
func1() {
console.log('func1 is called');
}
}
EventHub.off
off(event: string, callback?: Function): void;
取消订阅指定事件。当callback传值时,取消订阅指定的callback;未传值时,取消订阅该事件下所有callback。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:

示例:
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
onForeground() {
this.context.eventHub.on('123', this.func1);
this.context.eventHub.off('123', this.func1); //取消订阅func1
this.context.eventHub.on('123', this.func1);
this.context.eventHub.on('123', this.func2);
this.context.eventHub.off('123'); //取消订阅func1和func2
}
func1() {
console.log('func1 is called');
}
func2() {
console.log('func2 is called');
}
}
EventHub.emit
emit(event: string, …args: Object[]): void;
触发指定事件。
系统能力:SystemCapability.Ability.AbilityRuntime.Core
参数:

示例:
import Ability from '@ohos.app.ability.UIAbility';
export default class MainAbility extends Ability {
onForeground() {
this.context.eventHub.on('123', this.func1);
// 结果:
// func1 is called,undefined,undefined
this.context.eventHub.emit('123');
// 结果:
// func1 is called,1,undefined
this.context.eventHub.emit('123', 1);
// 结果:
// func1 is called,1,2
this.context.eventHub.emit('123', 1, 2);
}
func1(a, b) {
console.log('func1 is called,' + a + ',' + b);
}
}
审核编辑 黄宇
-
鸿蒙
+关注
关注
60文章
2862浏览量
45367
发布评论请先 登录
《鸿蒙设备学习菜鸟指南》之 【索引及PDF和工具分享】
《鸿蒙设备学习菜鸟指南》之 【三、安装】
《鸿蒙设备学习菜鸟指南》之 【五、搭建开发环境】
《鸿蒙设备学习菜鸟指南》之【七、开发】
【HarmonyOS HiSpark AI Camera试用连载 】初遇鸿蒙系统—6.基于HarmonyOS鸿蒙—北向HAP应用开发之2048小游戏
鸿蒙原生应用/元服务开发-Stage模型能力接口(五)
鸿蒙开发之ArkTS基础知识
鸿蒙开发教程
使用 Taro 开发鸿蒙原生应用 —— 快速上手,鸿蒙应用开发指南

鸿蒙开发之EventHub
评论