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.
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 popular:
- addListener / on
- removeListener / off
- hasListener / has
- dispatch / emit
Example:
import {EventEmitter} from 'chnl';
const emitter = new EventEmitter();
emitter.on('event', data => console.log(data));
emitter.emit('event', 'hello world!');
class MyClass extends 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:
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();