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