-
Notifications
You must be signed in to change notification settings - Fork 1
/
test-chat.js
82 lines (62 loc) · 1.9 KB
/
test-chat.js
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
$(function () {
var monitor = $.newChannel("OP Monitoring Channel"),
broadcast = $.newChannel("OP Broadcasting Channel");
// utility functions
function findParts(target) {
target = $(target);
return {
isOpRoom: target.is('#opRoom'),
name: $('h2', target).text(),
list: $('ul', target),
members: $.map($('div', target), function (mem) {
return {
name: $('strong', mem).text(),
input: $('input', mem),
sendButton: $('button', mem)
};
})
};
}
function formatMsg(msg) {
return "[" + msg.from + "] " + msg.msg;
}
// setup chat pub/sub
function setupChat(room) {
// send message to the channel on click
$(room.members).each(function () {
var me = this;
me.sendButton.click(function () {
$.publish(room, {
isBroadcast: room.isOpRoom,
from: me.name,
msg: me.input.val()
});
});
});
// append an item to the list on incoming messages
$.subscribe(room, function (msg) {
$(document.createElement("li"))
.text(formatMsg(msg))
.appendTo(room.list);
});
// logs all non-op room to the monitoring channel
// and make them receive all broadcasts
if (!room.isOpRoom) {
$.connect(broadcast, room);
$.connect(room, monitor, function (msg) {
if (msg.isBroadcast) return null; // prevents infinite loop
msg.from = msg.from + "@" + room.name;
return msg;
});
} else {
// op can see the monitor channel and can broadcasts messages
$.connect(monitor, room);
$.connect(room, broadcast, function (msg) {
return msg.isBroadcast ? msg : null; // prevents infinite loop
});
}
}
$(".chatroom").each(function () {
setupChat(findParts(this));
});
});