3 var DumbEventTarget = function() {
6 DumbEventTarget.prototype._ensure = function(type) {
7 if(!(type in this._listeners)) this._listeners[type] = [];
9 DumbEventTarget.prototype.addEventListener = function(type, listener) {
11 this._listeners[type].push(listener);
13 DumbEventTarget.prototype.emit = function(type) {
15 var args = Array.prototype.slice.call(arguments, 1);
16 if(this['on' + type]) this['on' + type].apply(this, args);
17 for(var i=0; i < this._listeners[type].length; i++) {
18 this._listeners[type][i].apply(this, args);
25 var MultiplexedWebSocket = function(ws) {
29 this.ws.addEventListener('message', function(e) {
30 var t = e.data.split(',');
31 var type = t.shift(), name = t.shift(), payload = t.join();
32 if(!(name in that.channels)) {
35 var sub = that.channels[name];
39 delete that.channels[name];
40 sub.emit('close', {});
43 sub.emit('message', {data: payload});
48 MultiplexedWebSocket.prototype.channel = function(raw_name) {
49 return this.channels[escape(raw_name)] =
50 new Channel(this.ws, escape(raw_name), this.channels);
54 var Channel = function(ws, name, channels) {
55 DumbEventTarget.call(this);
59 this.channels = channels;
60 var onopen = function() {
61 that.ws.send('sub,' + that.name);
64 if(ws.readyState > 0) {
65 setTimeout(onopen, 0);
67 this.ws.addEventListener('open', onopen);
70 Channel.prototype = new DumbEventTarget()
72 Channel.prototype.send = function(data) {
73 this.ws.send('msg,' + this.name + ',' + data);
75 Channel.prototype.close = function() {
77 this.ws.send('uns,' + this.name);
78 delete this.channels[this.name];
79 setTimeout(function(){that.emit('close', {})},0);