1.0.0 • Published 8 years ago

protected-event-emitter v1.0.0

Weekly downloads
1
License
Apache-2.0
Repository
github
Last release
8 years ago

protected-event-emitter

How is this event library different?

Any code can listen to any events but not any code can emit any event. This library allows you to control what code is allowed to emit what events.

Installation

$ npm install protected-event-emitter

API

emitter ( namespace )

Create an event emitter that will emit events on the specified namespace. The namespace must be unique.

Parameters

Returns an emit function that takes two parameters: 1) the type of event being emitted, and 2) the data for the event.

const event = require('protected-event-emmitter');
const emit = event.emitter('my-emitter');

emit('ready', 'Good to go');    // type is "ready", data is "Good to go"

listenerCount ( namespace , event )

Count how many item are listening the the namespace, optionally limiting results to a specific event type.

Parameters

Returns a number.

namespace ( namespace )

Get an object that has shortcut functions to the off, on, and once event handler functions for this namespace.

Parameters

Returns an object with event handler functions that are scoped to the namespace provided.

const event = require('protected-event-emmitter');

function readyHandler(data) {
    console.log('my-emiter is ready with data: ' + data);
}

const listeners = event.namespace('my-emitter');
listeners.on('ready', readyHandler);    // equivalent to: event.on('my-emitter', 'ready', readyHandler);
listeners.off('ready', readyHandler);   // equivalent to: event.off('my-emitter', 'ready', readyHandler);
listeners.once('ready', readyHandler);  // equivalent to: event.once('my-emitter', 'ready', readyHandler);

namespaces

A getter to get all namespaces that have been registered using the emitter function. Returns an array of strings.

off ( namespace, event, callback )

Remove an event handler from the specific namespace and event type.

Parameters

Returns undefined

const event = require('protected-event-emmitter');

function readyHandler(data) {
    console.log('my-emiter is ready with data: ' + data);
}

event.off('my-emitter', 'ready', readyHandler);

on ( namespace, event, callback )

Add an event handler from the specific namespace and event type.

Parameters

Returns undefined

const event = require('protected-event-emmitter');

function readyHandler(data) {
    console.log('my-emiter is ready with data: ' + data);
}

event.on('my-emitter', 'ready', readyHandler);

once ( namespace, event, callback )

Add an event handler from the specific namespace and event type that will only handle the event once.

Parameters

Returns undefined

const event = require('protected-event-emmitter');

function readyHandler(data) {
    console.log('my-emiter is ready with data: ' + data);
}

event.once('my-emitter', 'ready', readyHandler);