Learning Backbone
http://addyosmani.github.com/backbone-fundamentals/#prelude
by meetravi
HTML
<script src="https://raw.github.com/documentcloud/underscore/1.1.7/underscore.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/0.5.3/backbone.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
JavaScript
var Todo = Backbone.Model.extend({
// Default attributes for the todo
defaults: {
title: '',
completed: false
}
});
var Todos = Backbone.Collection.extend({
model: Todo,
// For simplicity we'll use localStorage throughout the first part of book.
// Save all of the todo items under the `"todos"` namespace.
localStorage: new Store('todos-backbone')
// When working with REST API on back-end here would be
// appropriate to use:
// url: "/todos"
});
var firstTodo = new Todo({title:'Read whole book'});
// pass array of models on collection instantiation
var todos = new Todos([firstTodo]);
console.log(todos.length);
// Collection's convenience method used to create
// new model instance within collection itself.
todos.create({title:'Try out code examples'});
console.log(todos.length);
var thirdTodo = new Todo({title:'Make something cool'});
// Adds model to collection
todos.add(thirdTodo);
console.log(todos.length);
// Collection keeps models in models
// property which is an array.
console.log(todos.models);