• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 公共事件发布
2
3
4## 场景介绍
5
6当需要发布某个自定义公共事件时,可以通过[publish()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerpublish)方法发布事件。发布的公共事件可以携带数据,供订阅者解析并进行下一步处理。
7
8> **须知:**
9> 已发出的粘性公共事件后来订阅者也可以接收到,其他公共事件都需要先订阅再接收,订阅参考[公共事件订阅章节](common-event-subscription.md)。
10
11
12## 接口说明
13
14详细接口见[接口文档](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerpublish)。
15
16| 接口名 | 接口描述 |
17| -------- | -------- |
18| publish(event: string, callback: AsyncCallback) | 发布公共事件。 |
19| publish(event: string, options: [CommonEventPublishData](../reference/apis/js-apis-commonEventManager.md#commoneventpublishdata), callback: AsyncCallback) | 指定发布信息并发布公共事件。 |
20
21
22## 发布不携带信息的公共事件
23
24不携带信息的公共事件,只能发布无序公共事件。
25
261. 导入模块。
27
28   ```ts
29   import commonEventManager from '@ohos.commonEventManager';
30   import Base from '@ohos.base';
31   ```
32
332. 传入需要发布的事件名称和回调函数,发布事件。
34
35   ```ts
36   // 发布公共事件
37   commonEventManager.publish("usual.event.SCREEN_OFF", (err: Base.BusinessError) => {
38       if (err) {
39           console.error(`[CommonEvent] PublishCallBack err=${JSON.stringify(err)}`);
40       } else {
41           console.info(`[CommonEvent] Publish success`);
42       }
43   });
44   ```
45
46
47## 发布携带信息的公共事件
48
49携带信息的公共事件,可以发布为无序公共事件、有序公共事件和粘性事件,可以通过参数[CommonEventPublishData](../reference/apis/js-apis-commonEventManager.md#commoneventpublishdata)的isOrdered、isSticky的字段进行设置。
50
511. 导入模块。
52
53   ```ts
54   import commonEventManager from '@ohos.commonEventManager';
55   import Base from '@ohos.base';
56   ```
57
582. 传入需要发布的事件名称和回调函数,发布事件。
59
60   ```ts
61   // 公共事件相关信息
62   let options: commonEventManager.CommonEventPublishData = {
63       code: 1, // 公共事件的初始代码
64       data: "initial data", // 公共事件的初始数据
65   }
66   ```
67
683. 传入需要发布的事件名称、需要发布的指定信息和回调函数,发布事件。
69
70   ```ts
71   // 发布公共事件
72   commonEventManager.publish("usual.event.SCREEN_OFF", options, (err: Base.BusinessError) => {
73       if (err) {
74           console.error('[CommonEvent] PublishCallBack err=' + JSON.stringify(err));
75       } else {
76           console.info('[CommonEvent] Publish success')
77       }
78   });
79   ```
80