forked from scottgonzalez/node-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodechat.js
More file actions
135 lines (120 loc) · 2.37 KB
/
Copy pathnodechat.js
File metadata and controls
135 lines (120 loc) · 2.37 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
(function($) {
var nodeChat = (window.nodeChat = {
connect: function(basePath) {
return new Channel(basePath);
}
});
function Channel(basePath) {
this.basePath = basePath;
bindAll(this);
}
$.extend(Channel.prototype, {
pollingErrors: 0,
lastMessageId: 0,
id: null,
request: function(url, options) {
var channel = this;
$.ajax($.extend({
url: this.basePath + url,
cache: false,
dataType: "json"
}, options));
},
poll: function() {
if (this.pollingErrors > 2) {
$(this).triggerHandler("connectionerror");
return;
}
var channel = this;
this.request("/recv", {
data: {
since: this.lastMessageId,
id: this.id
},
success: function(data) {
if (data) {
channel.handlePoll(data);
} else {
channel.handlePollError();
}
},
error: this.handlePollError
});
},
handlePoll: function(data) {
this.pollingErrors = 0;
var channel = this;
if (data && data.messages) {
$.each(data.messages, function(i, message) {
channel.lastMessageId = Math.max(channel.lastMessageId, message.id);
$(channel).triggerHandler(message.type, message);
});
}
this.poll();
},
handlePollError: function() {
this.pollingErrors++;
setTimeout(this.poll, 10*1000);
}
});
$.extend(Channel.prototype, {
join: function(nick, options) {
var channel = this;
this.request("/join", {
data: {
nick: nick
},
success: function(data) {
if (!data) {
(options.error || $.noop)();
return;
}
channel.id = data.id;
channel.since = data.since;
channel.poll();
(options.success || $.noop)();
},
error: options.error || $.noop
});
},
part: function() {
if (!this.id) { return; }
this.request("/part", {
data: { id: this.id }
});
},
send: function(msg) {
if (!this.id) { return; }
// TODO: use POST
this.request("/send", {
data: {
id: this.id,
text: msg
}
});
},
who: function() {
if (!this.id) { return; }
this.request("/who", {
success: function(data) {
var users = $("#users");
$.each(data.nicks, function(i, nick) {
users.append("<li>" + nick + "</li>");
});
}
});
}
});
function bind(fn, context) {
return function() {
return fn.apply(context, arguments);
};
}
function bindAll(obj) {
for (var prop in obj) {
if ($.isFunction(obj[prop])) {
obj[prop] = bind(obj[prop], obj);
}
}
}
})(jQuery);