se-bus

0.1.5 • Public • Published

Simple Event Bus

This is a simple event bus that can handle event communication.
Starting with version 0.1.3 it does also support browsers - so you can use the same module in both, server and client.
This module can be expanded by using a bridge to pass event from a server to a different server, or from a client to a server, or from a server to a client.
This bridge does use websocket; and is included in a different package, se-bus-ws. Please read the description of the bridge, that module is still under active development.

Demo

There is a working demo at gitlab. Its demonstrating the usage of se-bus and se-bus-ws by hosting a small web application that clients can use to connect in real time.

Usage (simple)

Event registration

import { on, once, many } from 'se-bus';

on('test', (params) => {
    console.log(`Will be called every time the "test" event will be emitted`);
});

once('test', (params) => {
    console.log(`Will be called once when the "test" event will be emitted`);
});

many(3, 'test', (params) => {
    console.log(`Will be called 3 times the "test" event will be emitted`);
});

Event emitting

import { on, emit } from 'se-bus';

on('greet', (params) => {
    console.log(`Hello ${params.name}`);
});

emit('greet', { name: 'Tino' });

Deregistering an event handler

Every call to on, once and many returns an object allowing to unregister it.

import { on, emit } from 'se-bus';

const eventInstance = on('greet', (params) => {
    // this will never be called
    console.log(`Hello ${params.name}`);
});

eventInstance.unregister();

emit('greet', { name: 'Tino' });

Usage for bulk event handling

This module allows to handle multiple event callbacks at once.
This can be useful when using e.g. Vue.JS: in a component register for multiple events on mount, on unmount unregister all event handler at once.

import { createEventStack, emit } from 'se-bus';

const eventStack = createEventStack();

eventStack
    .on('greet', (params) => {
        // This will be called every time the greet-event is being emitted
        console.log(`Hello ${params.name}`);
    })
    .once('greet', (params) => {
        // This will only be called once
        console.log(`Haven't seen you in a long time`);
    });

// Emit events as usual
emit('greet', { name: 'Tino' });

// Now unregister both events
eventStack.unregister();

Readme

Keywords

none

Package Sidebar

Install

npm i se-bus

Weekly Downloads

0

Version

0.1.5

License

MIT

Unpacked Size

19.5 kB

Total Files

18

Last publish

Collaborators

  • tionsys