通过commonEventManager模块实现,具体可参考如下代码:import { commonEventManager , BusinessError } from '@kit.BasicServicesKit'; export class SubscribeEvent { private static subscriber: commonEventManager.CommonEventSubscriber // 自定义的回调函数变量 private static callback: (a: BusinessError, b: commonEventManager.CommonEventSubscriber) => void /** * 创建订阅者 * @param subscribeInfo 订阅事件 * @callback 用户自定义回调函数 */ static createSubscriber(subscribeInfo: commonEventManager.CommonEventSubscribeInfo, callback: (err: BusinessError, commonEventSubscriber: commonEventManager.CommonEventSubscriber) => void) { SubscribeEvent.callback = callback commonEventManager.createSubscriber(subscribeInfo, (err: BusinessError, subscriber) => { if (err) { console.error('CreateSubscriberCallBack err = ' + JSON.stringify(err)) } else { SubscribeEvent.subscriber = subscriber; SubscribeEvent.subscribe(subscriber) console.info('Create subscriber succeed') } }) } /** * 订阅公共事件 * @param subscriber 订阅者 */ private static subscribe(subscriber: commonEventManager.CommonEventSubscriber) { if (subscriber != null) { commonEventManager.subscribe(subscriber, (err: BusinessError, data) => { if (err) { console.error('subscribe err = ' + JSON.stringify(err)) } else { console.info('SubscribeCallBack data= ' + JSON.stringify(data)) // this.callback('hello callback', data) } }) } else { console.info("Need create subscriber") } } } @Entry @Component struct Faq10_1 { @State message: string = '' // 发布公共事件回调 publishCB(err: BusinessError) { if (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } else { console.info("publish") ; } } build() { Row() { Column() { Text('订阅:' + this.message) .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { let subscribeInfo: commonEventManager.CommonEventSubscribeInfo = { events: ["myEvent"] }; let callback = (a: BusinessError, b: commonEventManager.CommonEventSubscriber) => { this.message = a.name } SubscribeEvent.createSubscriber(subscribeInfo, callback) }) Text('发布') .fontSize(30) .fontWeight(FontWeight.Bold) .onClick(() => { // 公共事件相关信息 let options: commonEventManager.CommonEventPublishData = { code: 0, // 公共事件的初始代码 data: "initial data", // 公共事件的初始数据 isOrdered: true // 有序公共事件 } // 发布公共事件 try { commonEventManager.publish("myEvent", options, this.publishCB); } catch (err) { console.error(`publish failed, code is ${err.code}, message is ${err.message}`); } }) } .width('100%') } .height('100%') } }参考链接公共事件模块
通过commonEventManager模块实现,具体可参考如下代码:
参考链接
公共事件模块