Backbone View Basics - Binding

by robdodson

HTML

<script src="http://underscorejs.org/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://raw.github.com/jeromegn/Backbone.localStorage/master/backbone.localStorage-min.js"></script>

JavaScript

var Book = Backbone.Model.extend({});

var BookView = Backbone.View.extend({
    className: 'book-view',
    initialize: function() {
        this.model.on('change', this.render, this);
        this.render();        
    },
    render: function() {
        this.$el.html(this.model.get('title') + ' by ' + this.model.get('author'));
    }
});

var outliers = new Book({
    author: 'Malcolm Gladwell',
    title: 'Outliers'
});

var bookView = new BookView({model: outliers});

$('body').append(bookView.el);

outliers.set('author', 'Mickey Mouse');