Backbone 101
A simple playground for learning backbone.js without having to install or configure anything yourself.
by dbouwman
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.marionette/1.0.3-bundled/backbone.marionette.min.js"></script>
<h1>Backbone 101</h1> <a id="show-drinks" href="#">Show Drinks</a>
<p>Drink Menu</p>
<ul id="commentList"></ul>
<div id="out"><h2>Debug Log:</h2></div>
<script type="text/template" id="comment-item-view-template">
<div class="comment-owner"><span class="icon-user"></span>{{=owner}}</div>
{{ if (type === 'comment' || type === 'annotation') { }}
<div class="comment">{{=comment}} </div>
{{ } else if ( type === 'version') { }}
<div class="comment">{{=type}}: {{=versionTitle}}</div>
{{ } }}
<div class='small-date'>{{=created}} </div>
</script>
CSS
@import url(http://fonts.googleapis.com/css?family=Molle:400italic);
h1 {
font-size:1.5em;
font-family:'Molle', cursive;
}
#out{margin-top:50px;}
ul li {margin:5px;cursor:pointer;border:1px solid #CCC;padding:10px;}
JavaScript
var data = [
{
owner: 'dbouwman',
comment: 'some comment text',
type:'annotation',
created: 1373031883000
}, {
owner: 'aturner',
type:'version',
versionTitle: 'Big New Map',
created: 1373028686000
}, {
owner: 'benheb',
type: 'comment',
comment: 'this is the bombdiggity',
created: 1373028675000
}];
var CommentModel = Backbone.Model.extend({});
var CommentCollection = Backbone.Collection.extend({
model: CommentModel,
comparator: function(model){
//this will sort the collection from largest to smallest on
//the unix timestamp - which is what we want
//don't use the datefield as that's
//console.log('comparator: ' + model.get('created'));
return -model.get('created');
}
});
var CommentItemView = Backbone.Marionette.ItemView.extend({
//define the model this view will work with
model: CommentModel,
//specify the template
template: '#comment-item-view-template',
//Specify the tag to wrap the template in
tagName:'li',
className: 'comment-item'
});
var CommentCollectionView = Backbone.Marionette.CollectionView.extend({
initialize: function(options){
_.bindAll(this);
},
//specify the tag name to wrap the collection in
tagName:'ul',
//specify the item view to use
itemView: CommentItemView,
//In order to have this collection view append in
//new items on top, we need to have this. Other
//option is to force a re-render
// appendHtml: function(collectionView, itemView){
// collectionView.$el.prepend(itemView.el);
// }
});
$('#show-drinks').on('click',function(){
var dataCollection = new CommentCollection(data);
var v = new CommentCollectionView({collection: dataCollection});
...