Backbone 101
A simple playground for learning backbone.js without having to install or configure anything yourself.
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>
<h1>Backbone 101</h1> <a id="show-drinks" href="#">Show Drinks</a>
<p>Drink Menu</p>
<ul id="menulist"></ul>
<div id="out"><h2>Debug Log:</h2></div>
<script type="text/template" id="menu-item-template">
<%= name %> Price: $<%= price %>
</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 = [{
name: 'Margarita',
price: '5.75'
}, {
name: 'Dos XX',
price: '5.00'
}, {
name: 'Corona',
price: '4.50'
}];
MenuItemModel = Backbone.Model.extend();
MenuItemCollection = Backbone.Collection.extend({
model:MenuItemModel
});
MenuView = Backbone.View.extend({
el: "#menulist",
render: function(){
var els = [];
this.collection.each(function(model){
var v = new MenuItemView({model:model});
els.push(v.render().el);
});
$(this.el).html(els);
}
});
MenuItemView = Backbone.View.extend({
tagName: 'li',
model: MenuItemModel,
template: _.template($('#menu-item-template').html()),
events: {'click':'itemClick'},
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
},
itemClick: function(){
$('#out').append('Thanks for the ' + this.model.get('name') + ' Jack! <br>');
}
});
$('#show-drinks').on('click',function(){
var dataCollection = new MenuItemCollection(data);
var v = new MenuView({collection: dataCollection});
v.render();
});