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
An object with the following keys and their values:
| Name | Type | Attributes | 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 event argument with the shape described in Event object. |
|
|
localOnly |
boolean |
<optional> |
When |
| 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 |
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
An object with the following keys and their values:
| Name | Type | Attributes | 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
}
});