• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Publishing Common Events
2
3
4## When to Use
5
6You can use [publish()](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerpublish) to publish a custom common event, which can carry data for subscribers to parse and process.
7
8> **NOTE**
9>
10> Subscribers can receive sticky common events that have been sent. However, they must subscribe to common events of other types before receiving them. For details about subscription, see [Subscribing to Common Events](common-event-subscription.md).
11
12
13## Available APIs
14
15For details about the APIs, see [API Reference](../reference/apis/js-apis-commonEventManager.md#commoneventmanagerpublish).
16
17| API| Description|
18| -------- | -------- |
19| publish(event: string, callback: AsyncCallback) | Publishes a common event.|
20| publish(event: string, options: [CommonEventPublishData](../reference/apis/js-apis-commonEventManager.md#commoneventpublishdata), callback: AsyncCallback) | Publishes a common event with given attributes.|
21
22
23## Publishing a Common Event That Does Not Carry Information
24
25Common events that do not carry information can be published only as unordered common events.
26
271. Import the **commonEventManager** module.
28
29   ```ts
30   import commonEventManager from '@ohos.commonEventManager';
31   ```
32
332. Pass in the common event name and callback, and publish the event.
34
35   ```ts
36   // Publish a common event.
37   commonEventManager.publish("usual.event.SCREEN_OFF", (err) => {
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## Publishing a Common Event That Carries Information
48
49Common events that carry information can be published as unordered, ordered, and sticky common events, which are specified by the **isOrdered** and **isSticky** fields of [CommonEventPublishData](../reference/apis/js-apis-commonEventManager.md#commoneventpublishdata).
50
511. Import the **commonEventManager** module.
52
53   ```ts
54   import commonEventManager from '@ohos.commonEventManager';
55   ```
56
572. Pass in the common event name and callback, and publish the event.
58
59   ```ts
60   // Attributes of a common event.
61   let options = {
62       code: 1, // Result code of the common event.
63       data: "initial data", // Result data of the common event.
64   }
65   ```
66
673. Pass in the common event name, attributes of the common event, and callback, and publish the event.
68
69   ```ts
70   // Publish a common event.
71   commonEventManager.publish("usual.event.SCREEN_OFF", options, (err) => {
72       if (err) {
73           console.error('[CommonEvent] PublishCallBack err=' + JSON.stringify(err));
74       } else {
75           console.info('[CommonEvent] Publish success')
76       }
77   })
78   ```
79