Backbone Model Basics

by robdodson

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<ul>
    <li id="author"></li>
    <li id="title"></li>
</ul>

JavaScript

// Create a book with some helpful defaults
var Book = Backbone.Model.extend({
    defaults: {
        author: 'Hunter S. Thompson',
        title: 'Fear and Loathing in Las Vegas'
    }
});

book = new Book();


// After the book is created set the #author and #title
// elements to reflect the state of the model
$('#author').html(book.get('author'));
$('#title').html(book.get('title'));

// Listen for a change to book author. When we hear a change
// update the #author element
book.on('change:author', function(model, author) {
  $('#author').html(book.get('author'));
});

// Change the book author
book.set('author', 'Mickey Mouse');