#5084 various improvements
Handle exceptions in JSON decoding, delay refresh when a code 200 occurs, handle channel subscription in the library
Showing
1 changed file
with
27 additions
and
9 deletions
1 | define([], function() { | 1 | define([], function() { |
2 | var listeners = []; | 2 | var channels = {}; |
3 | var messenger = { | 3 | var messenger = { |
4 | process: function() { | 4 | process: function() { |
5 | var self = this; | ||
5 | var url = "/comet/messenger" | 6 | var url = "/comet/messenger" |
6 | var request = new XMLHttpRequest(); | 7 | var request = new XMLHttpRequest(); |
7 | var responseLength = 0; | 8 | var responseLength = 0; |
... | @@ -13,9 +14,7 @@ define([], function() { | ... | @@ -13,9 +14,7 @@ define([], function() { |
13 | if (request.responseText) { | 14 | if (request.responseText) { |
14 | var newText = request.responseText.substr(responseLength); | 15 | var newText = request.responseText.substr(responseLength); |
15 | if (newText.length > 0) { | 16 | if (newText.length > 0) { |
16 | for (var i=0; i < listeners.length; i++) { | 17 | self.deliver(newText); |
17 | listeners[i](newText); | ||
18 | } | ||
19 | } | 18 | } |
20 | responseLength = request.responseText.length; | 19 | responseLength = request.responseText.length; |
21 | } | 20 | } |
... | @@ -34,14 +33,33 @@ define([], function() { | ... | @@ -34,14 +33,33 @@ define([], function() { |
34 | }; | 33 | }; |
35 | request.send(null); | 34 | request.send(null); |
36 | }, | 35 | }, |
36 | deliver: function(newText) { | ||
37 | try { | ||
38 | var json = JSON.parse(newText); | ||
39 | |||
40 | if (json.channel && channels[json.channel]) { | ||
41 | for (var i=0; i < channels[json.channel].length; i++) { | ||
42 | channels[json.channel][i](json); | ||
43 | } | ||
44 | } | ||
45 | } catch (err) { | ||
46 | console.log('Error processing COMETd message', newText, err); | ||
47 | } | ||
48 | }, | ||
37 | addListener: function(listener) { | 49 | addListener: function(listener) { |
38 | listeners.push(listener); | 50 | this.addListener('ALL', listener); |
39 | }, | 51 | }, |
40 | removeListener: function(listener) { | 52 | addListener: function(channel, listener) { |
41 | var index = listeners.indexOf(listener); | 53 | if (!channels[channel]) { |
42 | if (index > -1) { | 54 | channels[channel] = []; |
43 | array.splice(index, 1); | ||
44 | } | 55 | } |
56 | channels[channel].push(listener); | ||
57 | }, | ||
58 | removeListener: function(listener) { | ||
59 | this.removeListener('ALL', listener); | ||
60 | }, | ||
61 | removeListener: function(channel, listener) { | ||
62 | console.log('Remove listener from channel', listener, channel); | ||
45 | } | 63 | } |
46 | } | 64 | } |
47 | messenger.process(); | 65 | messenger.process(); | ... | ... |
-
Please register or sign in to post a comment