JSFiddle - React, Tailwind, and code Playground

by Rob Cameron

HTML

<!DOCTYPE html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>hello-backbonejs</title>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <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>

    <script src="...number.js..." type="text/javascript"></script>
  </body>
  </html>

JavaScript

(function($){
  var Item = Backbone.Model.extend({
    defaults: {
      part1: 'hello',
      part2: 'world'
    }
  });
  
  var List = Backbone.Collection.extend({
    model: Item
  });

  var ItemView = Backbone.View.extend({
    tagName: 'li',
      
    initialize: function(){
      _.bindAll(this, 'render');
    },
      
    render: function(){
      $(this.el).html('<span>'+this.model.get('part1')+' '+this.model.get('part2')+'</span>');
      return this;
    }
  });
  
  var ListView = Backbone.View.extend({
    el: $('body'),
      
    events: {
      'click button#add': 'addItem'
    },
      
    initialize: function(){
      _.bindAll(this, 'render', 'addItem', 'appendItem');
      
      this.collection = new List();
      this.collection.bind('add', this.appendItem);

      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){ 
        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);
    },
      
    appendItem: function(item){
      var itemView = new ItemView({
        model: item
      });
      $('ul', this.el).append(itemView.render().el);
    }
      
  });

  var listView = new ListView();
    
})(jQuery);