]> review.fuel-infra Code Review - packages/trusty/rabbitmq-server.git/blob
f525c1cc335a314890deeffb41f18a735ea60f98
[packages/trusty/rabbitmq-server.git] /
1 // ****
2
3 var DumbEventTarget = function() {
4     this._listeners = {};
5 };
6 DumbEventTarget.prototype._ensure = function(type) {
7     if(!(type in this._listeners)) this._listeners[type] = [];
8 };
9 DumbEventTarget.prototype.addEventListener = function(type, listener) {
10     this._ensure(type);
11     this._listeners[type].push(listener);
12 };
13 DumbEventTarget.prototype.emit = function(type) {
14     this._ensure(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);
19     }
20 };
21
22
23 // ****
24
25 var MultiplexedWebSocket = function(ws) {
26     var that = this;
27     this.ws = ws;
28     this.channels = {};
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)) {
33             return;
34         }
35         var sub = that.channels[name];
36
37         switch(type) {
38         case 'uns':
39             delete that.channels[name];
40             sub.emit('close', {});
41             break;
42         case 'msg':
43             sub.emit('message', {data: payload});
44             break
45         }
46     });
47 };
48 MultiplexedWebSocket.prototype.channel = function(raw_name) {
49     return this.channels[escape(raw_name)] =
50         new Channel(this.ws, escape(raw_name), this.channels);
51 };
52
53
54 var Channel = function(ws, name, channels) {
55     DumbEventTarget.call(this);
56     var that = this;
57     this.ws = ws;
58     this.name = name;
59     this.channels = channels;
60     var onopen = function() {
61         that.ws.send('sub,' + that.name);
62         that.emit('open');
63     };
64     if(ws.readyState > 0) {
65         setTimeout(onopen, 0);
66     } else {
67         this.ws.addEventListener('open', onopen);
68     }
69 };
70 Channel.prototype = new DumbEventTarget()
71
72 Channel.prototype.send = function(data) {
73     this.ws.send('msg,' + this.name + ',' + data);
74 };
75 Channel.prototype.close = function() {
76     var that = this;
77     this.ws.send('uns,' + this.name);
78     delete this.channels[this.name];
79     setTimeout(function(){that.emit('close', {})},0);
80 };