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
|
var ChatView = View.extend({
el: "#chat",
template: $("#message_template").html(),
events: {
"submit form": "send",
"scroll #messages": "scroll",
},
initialize: function(socket){
var $msg = this.$msg = this.$("#message")
this.$messages = this.$("#messages")
this.messages = this.$messages.get(0)
this.$msg.focus()
$(window).focus(function(){ $msg.focus() })
socket.on("message", function(msg){
base.chat.add(msg)
})
},
seen: {},
add: function(msg){
var key = msg.date + "_" + msg.nick
if (key in this.seen) return
this.seen[key] = true
var $el = $( this.template )
$el.find(".nick").html(sanitize(msg.nick))
$el.find(".msg").html(sanitizeHTML(msg.msg))
this.$messages.append($el)
if (! this.scrolled) {
this.scrollToBottom()
}
},
addMany: function(msgs){
var base = this
var wasScrolled = this.scrolled
this.scrolled = true
msgs.forEach(function(msg){
base.add(msg)
})
this.scrolled = wasScrolled
if (! this.scrolled) {
this.scrollToBottom()
}
},
send: function(e){
e && e.preventDefault()
var val = this.$msg.sanitize()
this.$msg.focus()
if (! val) return
this.$msg.val("")
var msg = {}
msg.room = room.name
msg.msg = val
msg.nick = user.username
msg.date = +new Date
this.add(msg)
app.socket.emit("message", msg)
},
empty: function(){
this.$messages.empty()
},
scrolled: false,
scroll: function(){
this.scrolled = (this.messages.scrollTop > this.messages.scrollHeight - this.$el.height() - 100)
},
scrollToBottom: function(){
this.messages.scrollTop = document.body.scrollHeight
}
})
|