dpaw-brocket-channel
Version:
Fundamental communication component
71 lines (59 loc) • 1.71 kB
JavaScript
/**
* @fileOverview
* @name channel.js
* @author Gavin Coombes
* @license BSD-3-License
*
* A channel object participates in the stream interface.
* A channel can be a
* - source channel
* - sink channel
* - transit channel.
*
* A source channel must have a subscribe method to pull messages out.
* A sink channel must have a dispatch method to push messages in.
* A transit channel must have both.
*/
let u = require('dpaw-brocket-utility');
let events = require('events');
// Local Aliases
var log = u.log;
var ChannelModule = (function(){
let obj = Object.create(new events.EventEmitter());
obj.$type = "ChannelModule";
return obj;
})();
var ChannelObject = Object.create(ChannelModule);
ChannelObject.$init = function init(opts){
let self = this;
self.opts = opts;
self.type = 'ChannelObject';
self.subscriptions = Object.create({});
};
ChannelObject.$subscribe = function subscribe(...args) {
/** Register a callback for each received message.
*
* Register a callback for every message.
* var f = msg => log('Received msg ', msg);
* relay.subscribe(f)
*
* Register a callback for messages with an appTag of 'bounds'
* var g = msg => log('Received bounds message');
* relay.subscribe('bounds', g)
*/
let self = this;
let [tag, cb] = args;
if (!cb) [tag, cb] = ['global', tag];
self.subscriptions = addSubscription(self.subscriptions, tag, cb);
};
module.exports = ChannelObject;
function create(parent, opts) {
let child = Object.create(parent);
child.init(opts);
return child;
}
function addSubscription(subs, key, val) {
if (!u.has(subs, key)) subs[key] = [];
subs[key] = [...subs[key], val];
return subs;
}