Selecting Strategy

You can choose how your event listener will be called when the event occurs by selecting an appropriate event publishing strategy. There are four built-in strategies: Synchronous, On-Next-Tick, Immediate and Delayed.

Synchronous Strategy

This strategy invokes event listeners in a synchronization model. Meaning listening functions will be called as soon as the event occurs. Thus removes all possible delays between event dispatching and event handling.

Synchronous Strategy is implicitly used by default. You can specify it explicitly by calling.sync() on builder:

aggregator.get('some event').sync().add(listener);

The significant drawback of this strategy is that it a blocking method and may drastically impact performance, especially in case of your handling function has some CPU-hungry blocking counterparts. You should only use Synchronous Strategy when the need for no-delay-listener is real, and only with lightweight handling functions.

On-Next-Tick Strategy

This strategy invokes listening functions on process.nextTick(), defers function invocation until the next event loop iteration.

To use it, call .nextTick() on builder:

aggregator.get('some event').nextTick().add(listener);

The statement above is equivalent to following statement using Synchronous Strategy:

aggregator.get('some event').add(payload => {
    process.nextTick(() => {
        listener(payload);
    });
})

Immediate Strategy

This is another deferring strategy, but invokes listening function by .setImmediate(). Thus makes function invocation a bit later than On-Next-Tick.

To use it, call .onImmediate() on builder:

aggregator.get('some event').immediate().add(listener);

The statement above is equivalent to:

aggregator.get('some event').add(payload => {
    var handle = setImmediate(() => {
        clearImmediate(handle);
        listener(payload);
    });
})

Delayed Strategy

This strategy delays invocation of listening function for a specified amount of time in milliseconds. It's useful in case of your component needs some time for initialization before handling the occurring event.

To use Delayed Strategy, call .delay() on builder:

aggregator.get('some event').delay(duration).add(listener);

The statement above is equivalent to:

aggregator.get('some event').add(payload => {
    var handle = setTimeout(() => {
        clearTimeout(handle);
        listener(payload);
    }, duration);
})

Last updated