Skip to content

Instantly share code, notes, and snippets.

@shubik
Last active December 20, 2015 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubik/6045849 to your computer and use it in GitHub Desktop.
Save shubik/6045849 to your computer and use it in GitHub Desktop.
var _ = require('underscore'),
redis = require('redis'),
redis_conf = require('../../servers/config/redis.json'),
cached = {},
Dispatcher = function(key) {
var self = this,
key_base = 'app:dispatcher:';
this.key = key_base + key;
this._pub = redis.createClient(redis_conf.port, redis_conf.host, redis_conf.options),
this._sub = redis.createClient(redis_conf.port, redis_conf.host, redis_conf.options);
this._sub.setMaxListeners(0);
this._sub.subscribe(this.key);
/* --- Subscribe to Redis only once ---*/
this._sub.on('message', function(ch, data) {
var payload = JSON.parse(data),
key = payload.evt + ':' + String(payload.id);
if (cached[key] && cached[key].length) {
for (var i = 0, j = cached[key].length; i < j; i++) {
cached[key][i](payload.data);
}
}
});
};
Dispatcher.prototype.emit = function(evt, id, data) {
var payload = {
evt : evt,
id : id,
data : data
};
this._pub.publish(this.key, JSON.stringify(payload));
}
Dispatcher.prototype.on = function(evt, id, callback) {
var key = evt + ':' + String(id);
cached[key] = cached[key] || [];
cached[key].push(callback);
}
Dispatcher.prototype.once = function(evt, id, callback) {
var key = evt + ':' + String(id);
delete cached[key];
cached[key] = [];
cached[key].push(callback);
}
Dispatcher.prototype.off = function(evt, id) {
var key = evt + ':' + String(id);
delete cached[key];
}
Dispatcher.prototype.flush = function() {
cached = {};
}
module.exports.devices = new Dispatcher('devices');
module.exports.sputniks = new Dispatcher('sputniks');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment