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); } }
審核編輯 黃宇
-
鴻蒙
+關注
關注
59文章
2508瀏覽量
43769
發布評論請先 登錄
《鴻蒙設備學習菜鳥指南》之 【索引及PDF和工具分享】
《鴻蒙設備學習菜鳥指南》之 【五、搭建開發環境】
《鴻蒙設備學習菜鳥指南》之【七、開發】
【HarmonyOS HiSpark AI Camera試用連載 】初遇鴻蒙系統—6.基于HarmonyOS鴻蒙—北向HAP應用開發之2048小游戲
鴻蒙原生應用/元服務開發-Stage模型能力接口(五)
鴻蒙系統是基于什么開發的
鴻蒙開發教程

使用 Taro 開發鴻蒙原生應用 —— 快速上手,鴻蒙應用開發指南

評論