-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroom.js
45 lines (39 loc) · 1.05 KB
/
room.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
var Room = function(userLimit) {
this.userLimit = userLimit
this.users = []
}
Room.prototype.addUser = function(user) {
if(this.hasRoom()) {
user.room = this
this.users.push(user);
this.sendToAll(user, 'new_user', {name: user.name})
for (i in this.users) {
user.socket.emit('get_current_users', {name: this.users[i].name})
}
return true;
} else { return false; }
}
Room.prototype.removeUser = function(user) {
var index = this.users.indexOf(user)
if(index != -1) {
this.users.splice(index, 1)
this.sendToAll(user, 'user_left', {name: user.name})
}
}
Room.prototype.sendToAll = function(sender, channel, message) {
for (i in this.users) {
var currentUser = this.users[i]
if(currentUser != sender) {
currentUser.socket.emit(channel, message)
}
}
}
Room.prototype.broadcast = function(channel, message) {
for (i in this.users) {
this.users[i].socket.emit(channel, message)
}
}
Room.prototype.hasRoom = function() {
return (this.users.length < this.userLimit)
}
module.exports = Room