EventHub模塊提供了事件中心,提供訂閱、取消訂閱、觸發(fā)事件的能力。
NOTE
本模塊首批接口從API version 9開始支持。后續(xù)版本的新增接口,采用上角標(biāo)單獨標(biāo)記接口的起始版本。
本模塊接口僅可在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;
訂閱指定事件。
系統(tǒng)能力:SystemCapability.Ability.AbilityRuntime.Core
參數(shù):
示例:
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'); }); // 結(jié)果: // 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;
取消訂閱指定事件。當(dāng)callback傳值時,取消訂閱指定的callback;未傳值時,取消訂閱該事件下所有callback。
系統(tǒng)能力:SystemCapability.Ability.AbilityRuntime.Core
參數(shù):
示例:
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;
觸發(fā)指定事件。
系統(tǒng)能力:SystemCapability.Ability.AbilityRuntime.Core
參數(shù):
示例:
import Ability from '@ohos.app.ability.UIAbility'; export default class MainAbility extends Ability { onForeground() { this.context.eventHub.on('123', this.func1); // 結(jié)果: // func1 is called,undefined,undefined this.context.eventHub.emit('123'); // 結(jié)果: // func1 is called,1,undefined this.context.eventHub.emit('123', 1); // 結(jié)果: // func1 is called,1,2 this.context.eventHub.emit('123', 1, 2); } func1(a, b) { console.log('func1 is called,' + a + ',' + b); } }
審核編輯 黃宇
-
鴻蒙
+關(guān)注
關(guān)注
59文章
2545瀏覽量
43841
發(fā)布評論請先 登錄
《鴻蒙設(shè)備學(xué)習(xí)菜鳥指南》之 【索引及PDF和工具分享】
《鴻蒙設(shè)備學(xué)習(xí)菜鳥指南》之 【五、搭建開發(fā)環(huán)境】
《鴻蒙設(shè)備學(xué)習(xí)菜鳥指南》之【七、開發(fā)】
【HarmonyOS HiSpark AI Camera試用連載 】初遇鴻蒙系統(tǒng)—6.基于HarmonyOS鴻蒙—北向HAP應(yīng)用開發(fā)之2048小游戲
鴻蒙原生應(yīng)用/元服務(wù)開發(fā)-Stage模型能力接口(五)
鴻蒙系統(tǒng)是基于什么開發(fā)的
鴻蒙系統(tǒng)是基于什么開發(fā)的
鴻蒙開發(fā)教程

使用 Taro 開發(fā)鴻蒙原生應(yīng)用 —— 快速上手,鴻蒙應(yīng)用開發(fā)指南

評論