1# EventHub
2
3EventHub模块提供了事件中心,提供订阅、取消订阅、触发事件的能力。
4
5> **说明:**
6>
7>  - 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8>  - 本模块接口仅可在Stage模型下使用。
9
10## 导入模块
11
12```ts
13import { common } from '@kit.AbilityKit';
14```
15
16## 使用说明
17
18在使用eventHub的功能前,需要通过UIAbility实例的成员变量context获取。
19
20```ts
21import { UIAbility } from '@kit.AbilityKit';
22
23export default class EntryAbility extends UIAbility {
24  eventFunc() {
25    console.log('eventFunc is called');
26  }
27
28  onCreate() {
29    this.context.eventHub.on('myEvent', this.eventFunc);
30  }
31}
32```
33EventHub不是全局的事件中心,不同的context对象拥有不同的EventHub对象,事件的订阅、取消订阅、触发都作用在某一个具体的EventHub对象上,因此不能用于虚拟机间或者进程间的事件传递。
34
35## EventHub.on
36
37on(event: string, callback: Function): void;
38
39订阅指定事件。
40> **说明:**
41>
42>  callback被emit触发时,调用方是EventHub对象,如果要修改callback中this的指向,可以使用箭头函数。
43
44**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
45
46**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
47
48**参数:**
49
50| 参数名 | 类型 | 必填 | 说明 |
51| -------- | -------- | -------- | -------- |
52| event | string | 是 | 事件名称。 |
53| callback | Function | 是 | 事件回调,事件触发后调用。 |
54
55**错误码**:
56
57以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
58
59| 错误码ID | 错误信息 |
60| ------- | -------- |
61| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
62
63**示例1:**
64callback被emit触发时,调用方是EventHub对象。EventHub对象没有value属性,因此结果是undefined。
65
66```ts
67import { UIAbility } from '@kit.AbilityKit';
68import { BusinessError } from '@kit.BasicServicesKit';
69
70export default class EntryAbility extends UIAbility {
71  value: number = 12;
72
73  onCreate() {
74    try {
75      this.context.eventHub.on('myEvent', this.eventFunc);
76    } catch (e) {
77      let code: number = (e as BusinessError).code;
78      let msg: string = (e as BusinessError).message;
79      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
80    }
81  }
82
83  onForeground() {
84    try {
85      // 结果:
86      // eventFunc is called, value: undefined
87      this.context.eventHub.emit('myEvent');
88    } catch (e) {
89      let code: number = (e as BusinessError).code;
90      let msg: string = (e as BusinessError).message;
91      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
92    }
93  }
94
95  eventFunc() {
96    console.log(`eventFunc is called, value: ${this.value}`);
97  }
98}
99```
100
101**示例2:**
102callback使用箭头函数时,调用方是EntryAbility对象。EntryAbility对象里存在value属性,因此结果是12。
103
104```ts
105import { UIAbility } from '@kit.AbilityKit';
106import { BusinessError } from '@kit.BasicServicesKit';
107
108export default class EntryAbility extends UIAbility {
109  value: number = 12;
110
111  onCreate() {
112    try {
113      // 支持使用匿名函数订阅事件
114      this.context.eventHub.on('myEvent', () => {
115        console.log(`anonymous eventFunc is called, value: ${this.value}`);
116      });
117    } catch (e) {
118      let code: number = (e as BusinessError).code;
119      let msg: string = (e as BusinessError).message;
120      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
121    }
122  }
123
124  onForeground() {
125    try {
126      // 结果:
127      // anonymous eventFunc is called, value: 12
128      this.context.eventHub.emit('myEvent');
129    } catch (e) {
130      let code: number = (e as BusinessError).code;
131      let msg: string = (e as BusinessError).message;
132      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
133    }
134  }
135
136  eventFunc() {
137    console.log(`eventFunc is called, value: ${this.value}`);
138  }
139}
140```
141
142## EventHub.off
143
144off(event: string, callback?: Function): void;
145
146取消订阅指定事件。
147 - 传入callback:取消指定的callback对指定事件的订阅,当该事件触发后,将不会回调该callback。
148 - 不传callback:取消所有callback对指定事件的订阅。
149
150**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
151
152**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
153
154**参数:**
155
156| 参数名 | 类型 | 必填 | 说明 |
157| -------- | -------- | -------- | -------- |
158| event | string | 是 | 事件名称。 |
159| callback | Function | 否 | 事件回调。如果不传callback,则取消订阅该事件下所有callback。 |
160
161**错误码**:
162
163以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
164
165| 错误码ID | 错误信息 |
166| ------- | -------- |
167| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
168
169**示例:**
170
171```ts
172import { UIAbility } from '@kit.AbilityKit';
173import { BusinessError } from '@kit.BasicServicesKit';
174
175export default class EntryAbility extends UIAbility {
176  onCreate() {
177    try {
178      this.context.eventHub.on('myEvent', this.eventFunc1);
179      this.context.eventHub.off('myEvent', this.eventFunc1); // 取消eventFunc1对myEvent事件的订阅
180      this.context.eventHub.on('myEvent', this.eventFunc1);
181      this.context.eventHub.on('myEvent', this.eventFunc2);
182      this.context.eventHub.off('myEvent'); // 取消eventFunc1和eventFunc2对myEvent事件的订阅
183    } catch (e) {
184      let code: number = (e as BusinessError).code;
185      let msg: string = (e as BusinessError).message;
186      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
187    }
188  }
189
190  eventFunc1() {
191    console.log('eventFunc1 is called');
192  }
193
194  eventFunc2() {
195    console.log('eventFunc2 is called');
196  }
197}
198```
199
200## EventHub.emit
201
202emit(event: string, ...args: Object[]): void;
203
204触发指定事件。
205
206**原子化服务API**:从API version 11开始,该接口支持在原子化服务中使用。
207
208**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
209
210**参数:**
211
212| 参数名 | 类型 | 必填 | 说明 |
213| -------- | -------- | -------- | -------- |
214| event | string | 是 | 事件名称。 |
215| ...args | Object[] | 否 | 可变参数,事件触发时,传递给回调函数的参数。 |
216
217**错误码**:
218
219以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
220
221| 错误码ID | 错误信息 |
222| ------- | -------- |
223| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
224
225**示例:**
226
227```ts
228import { UIAbility } from '@kit.AbilityKit';
229import { BusinessError } from '@kit.BasicServicesKit';
230
231export default class EntryAbility extends UIAbility {
232  onCreate() {
233    this.context.eventHub.on('myEvent', this.eventFunc);
234  }
235
236  onDestroy() {
237    try {
238      // 结果:
239      // eventFunc is called,undefined,undefined
240      this.context.eventHub.emit('myEvent');
241      // 结果:
242      // eventFunc is called,1,undefined
243      this.context.eventHub.emit('myEvent', 1);
244      // 结果:
245      // eventFunc is called,1,2
246      this.context.eventHub.emit('myEvent', 1, 2);
247    } catch (e) {
248      let code: number = (e as BusinessError).code;
249      let msg: string = (e as BusinessError).message;
250      console.error(`EventHub emit error, code: ${code}, msg: ${msg}`);
251    }
252  }
253
254  eventFunc(argOne: number, argTwo: number) {
255    console.log(`eventFunc is called, ${argOne}, ${argTwo}`);
256  }
257}
258```
259