Backbonejs Hello World use model

use default model add list li

by erick

HTML

<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
<h1><b>Learn How to use Backbone JS</b></h1>
<hr>
<hr>
<hr>

JavaScript

(function($){
   var Item = Backbone.Model.extend({
    defaults: {
      part1: 'hello',
      part2: 'bos'
    }
  });
    var List = Backbone.Collection.extend({
    model: Item
  });
    var ListView = Backbone.View.extend({
    el: $('body'),
    events: {
      'click button#add': 'addItem'
    },
    initialize: function(){
         _.bindAll(this, 'render', 'addItem', 'appendItem'); // remember: every function that uses 'this' as the current object should be in here
      
      this.collection = new List();
      this.collection.bind('add', this.appendItem); // collection event binder

      this.counter = 0;
      this.render();      
    },
    render: function(){
    var self = this;      
      $(this.el).append("<button id='add'>Add list item</button>");
      $(this.el).append("<ul></ul>");
      _(this.collection.models).each(function(item){ // in case collection is not empty
        self.appendItem(item);
      }, this);
    },
    addItem: function(){
      this.counter++;
      var item = new Item();
      item.set({
        part2: item.get('part2') + this.counter // modify item defaults
      });
      this.collection.add(item); // add item to collection; view is updated via event 'add'
    },
    appendItem: function(item){
      $('ul', this.el).append("<li>"+item.get('part1')+" "+item.get('part2')+"</li>");
    }
  });
      var listView = new ListView();
})(jQuery);  


//Note: render() now introduces a button to add a new list item.
//      initialize(): Automatically called upon instantiation. Where you make all types of bindings, excluding UI events, such as clicks, etc.