Skip to content

Instantly share code, notes, and snippets.

@retro
Created April 13, 2012 12:44
Show Gist options
  • Save retro/2376672 to your computer and use it in GitHub Desktop.
Save retro/2376672 to your computer and use it in GitHub Desktop.
Implementation of Firebase chat demo with CanJS. Uses observable and live binding
<html>
<head>
<title>CanJS Firebase chat demo</title>
<script type='text/javascript' src='http://static.firebase.com/demo/firebase.js'></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript" src="http://retro.github.com/javascripts/can.jquery.js"></script>
<link rel='stylesheet' type='text/css' href='http://www.firebase.com/css/example.css'>
</head>
<body>
<div id='messagesDiv'></div>
<input type='text' id="nameInput" placeholder='Name'>
<input type='text' id='messageInput' placeholder='Message'>
<script type="text/ejs" id="chatEJS">
<% list(this, function(msg){ %>
<div><em><%= msg.attr('name') %></em>: <%= msg.attr('text') %></div>
<% }) %>
</script>
<script type='text/javascript'>
Store = new Firebase('http://demo.firebase.com/Retro318372046');
MessagesList = can.Observe.List({}, {
init : function(){
var self = this;
Store.on('child_added', function(snapshot){
var msg = snapshot.val()
self.push({text: msg.text, name: msg.name})
})
},
addMessage : function(msg){
Store.push(msg)
}
})
Chat = can.Control({
defaults : {
list: new MessagesList
}
}, {
init : function(){
this.element.find('#messagesDiv').html(can.view('chatEJS', this.options.list));
},
"#messageInput keypress" : function(el, ev){
if(ev.keyCode === 13){
var name = this.element.find('#nameInput').val(),
text = el.val()
this.options.list.addMessage({name: name, text: text});
el.val("");
}
}
})
new Chat($('body'))
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment