EventHub
EventHub模塊提供了事件中心,提供訂閱、取消訂閱、觸發事件的能力。
說明:
開發前請熟悉鴻蒙開發指導文檔 :[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]點擊或者復制轉到。
本模塊首批接口從API version 9開始支持。后續版本的新增接口,采用上角標單獨標記接口的起始版本。
本模塊接口僅可在Stage模型下使用。
使用說明
?在使用eventHub的功能前,需要通過Ability實例的成員變量context獲取。
import Ability from '@ohos.application.Ability'
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
參數:
參數名 | 類型 | 必填 | 說明 |
---|---|---|---|
event | string | 是 | 事件名稱。 |
callback | Function | 是 | 事件回調,事件觸發后運行。 |
示例:
import Ability from '@ohos.application.Ability'
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
參數:
參數名 | 類型 | 必填 | 說明 |
---|---|---|---|
event | string | 是 | 事件名稱。 |
callback | Function | 否 | 事件回調。如果不傳callback,則取消訂閱該事件下所有callback。 |
示例:
import Ability from '@ohos.application.Ability'
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
參數:
參數名 | 類型 | 必填 | 說明HarmonyOS與OpenHarmony鴻蒙文檔籽料:mau123789是v直接拿 |
---|---|---|---|
event | string | 是 | 事件名稱。 |
...args | Object[] | 是 | 可變參數,事件觸發時,傳遞給回調函數的參數。 |
示例:
import Ability from '@ohos.application.Ability'
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);
}
}
-
移動開發
+關注
關注
0文章
52瀏覽量
9836 -
鴻蒙系統
+關注
關注
183文章
2638瀏覽量
66705 -
HarmonyOS
+關注
關注
79文章
1982瀏覽量
30573 -
OpenHarmony
+關注
關注
25文章
3744瀏覽量
16577 -
鴻蒙OS
+關注
關注
0文章
190瀏覽量
4537
發布評論請先 登錄
相關推薦
評論