Event library
Contents
This API provides functions to create and listen to instance local or cluster distributed events.
Usage
Add the following to your build.gradle file:
dependencies {
include xplibs.event
}
Add the import statement to your code:
import eventLib from '/lib/xp/event';
You are now ready to use the API.
|
Several standard XP APIs already produce and publish events. For more details, check out the Node library, Repo library, and Task library |
Functions
listener
Registers an event listener that fires for events whose type matches the given pattern.
Parameters
listener() takes a single ListenerParams object with these properties:
| Name | Type | Description |
|---|---|---|
|
type |
string |
Event type pattern. Works like a Java pattern, with two key differences: |
|
callback |
function |
Function invoked for each matching event. Receives a single argument, an EnonicEvent object. |
|
localOnly |
boolean |
Optional. When |
Returns
void
Example
import {listener} from '/lib/xp/event';
listener({
type: 'node.*',
localOnly: false,
callback: (event) => {
log.info('event: %s', JSON.stringify(event));
}
});
send
Sends a custom event. The supplied type is automatically prefixed with custom. before the event is published.
Parameters
send() takes a single SendParams object with these properties:
| Name | Type | Description |
|---|---|---|
|
type |
string |
Event type. Will be published as |
|
distributed |
boolean |
Optional. When |
|
data |
object |
Optional. Additional data to attach to the event payload. |
Returns
void
Example
import {send} from '/lib/xp/event';
send({
type: 'myEvent',
distributed: false,
data: {
a: 1,
b: 2
}
});
Type Definitions
EnonicEvent
The object passed to a listener callback for each matching event.
Properties
| Name | Type | Description |
|---|---|---|
|
type |
string |
Event type, for example |
|
timestamp |
number |
Time the event was published, in milliseconds since the epoch. |
|
localOrigin |
boolean |
|
|
distributed |
boolean |
|
|
data |
object |
Event payload. Shape depends on the event |