-
Notifications
You must be signed in to change notification settings - Fork 1
/
myApp.js
81 lines (68 loc) · 1.97 KB
/
myApp.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
Messages = new Meteor.Collection("messages");
Online = new Meteor.Collection("online");
Connections = new Meteor.Collection("connections");
numUsers = 0
if (Meteor.isClient) {
Template.display.messages = function () {
return Messages.find({}, {sort: {date_created: 1}});
};
Template.online.users = function () {
return Online.find({}, {sort: {date_created: -1}})
}
// client code: ping heartbeat every 5 seconds
Meteor.setInterval(function () {
Meteor.call('keepalive', Session.get('id'));
}, 1000);
Template.input.events({
"keypress #input" : function (e) {
if (e['shiftKey'] && e.which == 13) {
null
}
else if (e.which == 13) {
e.preventDefault()
textarea = document.getElementsByTagName('textarea')[0]
Messages.insert({
message: textarea.value,
date_created: Date.parse(Date()),
creator: Session.get("name")
});
textarea.value = "";
}
},
"click #kill" : function () {
Messages.remove({})
}
});
Meteor.startup(function () {
var user_name = String(prompt("What is your name?", "Bob"))
Session.setDefault("name", user_name)
Session.set("id", numUsers)
Online.insert({
name: user_name,
joined: Date.parse(Date()),
id: numUsers,
last_seen: (new Date()).getTime()
})
numUsers += 1
$(window).bind('beforeunload', function() {
Online.remove({id: Session.get("id")})
});
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
// Online.remove({})
});
// server code: heartbeat method
Meteor.methods({
keepalive: function (user_id) {
Online.update({id: user_id}, {$set: {last_seen: (new Date()).getTime()}})
}
});
// server code: clean up dead clients after 1 second
Meteor.setInterval(function () {
var now = (new Date()).getTime();
var inactiveUsers = Online.find({last_seen: {$lt: (now - 2000)}})
});
}