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: . is treated as a literal dot (not a wildcard), and acts as ., matching any sequence of characters.

callback

function

Function invoked for each matching event. Receives a single event argument with the shape described in Event object.

localOnly

boolean

<optional>

When true, only events originating on the current node are delivered. Defaults to false.

Event object passed to the callback
Name Type Description

type

string

Event type, for example node.pushed or custom.myEvent.

timestamp

number

Time the event was published, in milliseconds since the epoch.

localOrigin

boolean

true if the event was published on the current node, false if it was received from another cluster node.

distributed

boolean

true if the event was distributed across the cluster.

data

object

Event payload. Shape depends on the event type; for built-in node events, see Node library.

Returns

void

Example

Adding a listener that logs every node event
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 custom.<type>.

distributed

boolean

<optional>

When true, the event is broadcast to every node in the cluster. Defaults to false.

data

object

<optional>

Additional data to attach to the event payload.

Returns

void

Example

Send a custom event into the system
import {send} from '/lib/xp/event';

send({
    type: 'myEvent',
    distributed: false,
    data: {
        a: 1,
        b: 2
    }
});

Contents

Contents