Chrome compatible javascript channels
![npm version](https://badge.fury.io/js/chnl.svg)
Implementation of channels (aka events, pub/sub, dispatcher) inspired and
compatible with Chrome extensions events API.
Additionally, there are some extra features (e.g. passing context
with listener) and utility classes
that makes life easier.
Installation
npm i chnl --save
Classes overview
- Channel - chrome-like event channel
- EventEmitter - nodejs-like event emitter based on channels
- Subscription - class allowing to dynamically attach/detach batch of listeners
Channel
Channel is class that can attach/detach listeners and dispatch data to them.
This allows to make more independent modules that just produce events in outer world.
API:
- addListener
- removeListener
- hasListener
- hasListeners
- dispatch
- mute
- unmute
Example:
module A
import Channel from 'chnl';
exports.onChanged = new Channel();
exports.onChanged.dispatch(data);
module B
import moduleA from './moduleA';
moduleA.onChanged.addListener(data => {
console.log('moduleA.onChanged', data);
});
moduleA.onChanged.addOnceListener(data => {
console.log('moduleA.onChanged once', data);
});
moduleA.onChanged.mute({accumulate: true});
moduleA.onChanged.unmute();
EventEmitter
EventEmitter is basically a group of channels with common api.
The main difference from single channel is that each method takes additional event
argument.
Not all methods of original nodejs EventEmitter
are supported but most needed:
- addListener / on
- removeListener / off
- hasListener / has
- dispatch / emit
Example:
import Channel from 'chnl';
const emitter = new Channel.EventEmitter();
emitter.on('event', data => console.log(data));
emitter.emit('event', 'hello world!');
class MyClass extends Channel.EventEmitter {
someMethod() {
this.emit('event', 'hello world!')
}
}
const myClass = new MyClass();
myClass.on('event', data => console.log(data));
myClass.someMethod();
Subscription
Subscription is utility class allowing dynamically attach/detach batch of listeners to event channels.
You pass array of {channel: ..., event: ..., listener: ...}
to constructor and then manage it via two methods:
Example:
import Channel from 'chnl';
this._subscription = new Channel.Subscription([
{
channel: chrome.tabs.onUpdated,
listener: this._onTabUpdated.bind(this)
},
{
channel: document.getElementById('button'),
event: 'click',
listener: this._onButtonClick.bind(this)
}
]);
this._subscription.on();
this._subscription.off();