Backbone.js Todo Example
by Budhram Gurung
HTML
<script src="https://rawgithub.com/douglascrockford/JSON-js/master/json2.js"></script>
<script src="https://rawgithub.com/jashkenas/underscore/1.5.2/underscore-min.js"></script>
<script src="https://rawgithub.com/jashkenas/backbone/1.0.0/backbone-min.js"></script>
<script src="https://rawgithub.com/jeromegn/Backbone.localStorage/v1.1.6/backbone.localStorage.js"></script>
<div id="app"></div>
CSS
body {
font-size: 14px;
background: #eeeeee;
color: #333333;
width: 520px;
margin: 0 auto;
}
#todoapp {
background: #fff;
padding: 20px;
margin-bottom: 40px;
}
#todoapp h1 {
font-size: 36px;
text-align: center;
}
#todoapp input[type="text"] {
width: 466px;
font-size: 24px;
line-height: 1.4em;
padding: 6px;
}
#main {
display: none;
}
#todo-list {
margin: 10px 0;
padding: 0;
list-style: none;
}
#todo-list li {
padding: 18px 20px 18px 0;
position: relative;
font-size: 24px;
border-bottom: 1px solid #cccccc;
}
#todo-list li:last-child {
border-bottom: none;
}
#todo-list li.done label {
color: #777777;
text-decoration: line-through;
}
#todo-list li .edit {
display: none;
}
#todo-list li.editing {
border-bottom: 1px solid #778899;
}
#todo-list li.editing .view {
display: none;
}
#todo-list li.editing .edit {
display: block;
width: 444px;
padding: 13px 15px 14px 20px;
margin: 0;
}
#todo-list li.done label {
color: #777777;
text-decoration: line-through;
}
#todo-list .destroy {
position: absolute;
right: 5px;
top: 20px;
display: none;
cursor: pointer;
width: 20px;
height: 20px;
}
#todoapp footer {
display: none;
margin: 0 -20px -20px -20px;
overflow: hidden;
color: #555555;
background: #f4fce8;
border-top: 1px solid #ededed;
padding: 0 20px;
line-height: 37px;
}
#clear-completed {
float: right;
line-height: 20px;
text-decoration: none;
background: rgba(0, 0, 0, 0.1);
color: #555555;
font-size: 11px;
margin-top: 8px;
margin-bottom: 8px;
padding: 0 10px 1px;
cursor: pointer;
}
JavaScript
$(function(){
var WorldEvent = Backbone.Model.extend({});
var WorldEventView = Backbone.View.extend({
events: {
'click' : 'focusEvent'
},
focusEvent: function(){
alert('great.');
},
className : 'pin bounce',
render : function () {
console.log('did something');
this.$el.html("rendered");
}
});
var WorldEventCollection = Backbone.Collection.extend({
model: WorldEvent,
url: '/events'
});
var worldEventCollection = new WorldEventCollection();
var worldEventCollectionView = new WorldEventView({
el: '#app',
collection: worldEventCollection,
initialize: function(){
console.log('inside app');
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
addOne: function(myEvent){
var worldEventView = new WorldEventView({ model: myEvent });
this.$el.append(worldEventView.render().el);
},
addAll: function(){
this.collection.forEach(this.addOne, this);
},
render: function(){
this.addAll();
}
});
}());