Model example in Backbone.js

Simple example of how models work in Backbone.js Shows two views listening to the same model and updating themselves when changes occur.

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
 <h1>Models in Backbone.js</h1> 
<p>Enter a name in the input below</p>
<div id="message-container">
    <input id="name" />
    <button id="button">Save</button>
    <br /> <span id="message"></span>

    <br />
</div>
<div id="name-container"></div>
<script type="text/template" id="message-template">
    Welcome to Backbone <%= name %>
</script>
<script type="text/template" id="name-template">
    Person: <%= name %>
</script>

SCSS

body { margin: 30px;}
body {font-family: Arial;}
h1{font-weight:bold;font-size:16px;}
p{margin:5px 0px 5px 0px;}

JavaScript

var MessageView = Backbone.View.extend({
      template: _.template($('#message-template').html()),
      events: {
          'click #button': 'updateModel'
      },
      updateModel: function (event) {
          this.model.set({
              name: $("#name").val()
          });
          $("#name").html('');
      },
      initialize: function () {
          _.bindAll(this, 'render');
          this.listenTo(this.model, "change", this.render);
      },
      render: function () {
          this.$('#message').html(this.template(this.model.toJSON()));
          return this;
      }
  });

  var NameView = Backbone.View.extend({
      template: _.template($('#name-template').html()),
      initialize: function () {
          _.bindAll(this, 'render');
          this.listenTo(this.model, "change", this.render);
      },
      render: function () {
          this.$el.html(this.template(this.model.toJSON()));
          return this;
      }
  });

  var Person = Backbone.Model.extend({
      defaults: {
          name: ''
      }
  });

  var person = new Person();

  var messageView = new MessageView({
      el: $('#message-container'),
      model: person
  });

  var nameView = new NameView({
      el: $('#name-container'),
      model: person
  });