public
Created

Stopgap channel implementation

  • Download Gist
now-channel.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
var Channel = (function () {
function Channel(name) {
this.init(name);
}
Channel.prototype = new Object();
// Initialise
Channel.prototype.init = function (name) {
this.name = name;
this.clients = {};
this.connectedFuncs = [];
this.disconnectedFuncs = [];
}
// Utility function to iterate over clients in the channel.
Channel.prototype.iterate = function (callback) {
_(this.clients).each(function (client) {
callback.call(client);
});
}
// Add a callback on client connection to the channel.
Channel.prototype.connected = function (callback) {
this.connectedFuncs.push(callback);
}
Channel.prototype.runConnected = function (client) {
_(this.connectedFuncs).each(function (callback) {
callback.call(client);
});
}
// Add a callback on client disconnection from the channel.
Channel.prototype.disconnected = function (callback) {
this.disconnectedFuncs.push(callback);
}
Channel.prototype.runDisconnected = function (client) {
_(this.disconnectedFuncs).each(function (callback) {
callback.call(client);
});
}
// Join a client to the channel and trigger connected callbacks.
Channel.prototype.join = function (client) {
this.clients[client.user.clientId] = client;
this.runConnected(client);
}
// Remove a client from the channel and trigger disconnected callbacks.
Channel.prototype.leave = function (client) {
if (this.clients[client.user.clientId]) {
delete this.clients[client.user.clientId];
this.runDisconnected(client);
}
}
// Takes a function name and a callback as a function to call for each
// client in the channel.
Channel.prototype.def = function (funcname, callback) {
if (this[funcname] !== undefined) {
console.log("Ignored def for " + funcname + " as it was already defined.");
}
this[funcname] = function () {
var args = arguments;
_(this.clients).each(function (client) {
callback.apply(client, args);
});
}
}
// Takes 1 or more arguments as function names to proxy forward to clients
// that are in the channel.
Channel.prototype.proxy = function () {
for (var i = 0; i < arguments.length; i++) {
var funcname = arguments[i];
if (this[funcname] !== undefined) {
console.log("Ignored def for " + funcname + " as it was already defined.");
}
this[funcname] = function () {
var args = arguments;
_(this.clients).each(function (client) {
client.now[funcname].apply(client, args);
});
}
}
}
return Channel;
}());

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.