Simple Backbone.ModelBinding Example

shows how simple modelbinding can be with the Backbone.ModelBinding plugin from http://github.com/derickbailey/backbone.modelbinding

by Nirvanachain

HTML

<script src="https://raw.github.com/documentcloud/underscore/1.1.7/underscore.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/0.5.3/backbone.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.modelbinding/v0.2.1/backbone.modelbinding.js"></script>
<div id="friends">
  <input type="text" placeholder="Enter friend's name" id="input" />
  <button id="add-input">Add Friend</button>

  <ul id="friends-list">
  </ul>
</div>

JavaScript

$(function() {

        FriendList = Backbone.Collection.extend();
        
        FriendListView = Backbone.View.extend({
            initialize: function(e, c) {
                this.collection.bind('add', this.render, this);
                this.collection.bind('remove', this.render, this);
            },
            
            events: {
                'click #add-input':  'addFriend'
            },
            
            addFriend: function() {
                var friend_name = $('#input').val();
                $('#input').val('');
                this.collection.add({name: friend_name});
            },
            
            render: function() {
                var list = this.el.find('#friends-list');
                list.empty();
                this.collection.each(function(model) {
                    var friendView = new FriendView({model: model});
                    list.append(friendView.render().el);
                });
            }
        });

        FriendView = Backbone.View.extend({

            tagName: 'li',

            events: {
                'click .button': 'removeFriend'
            },

            removeFriend: function(){
                this.model.collection.remove(this.model);
            },
            
            render: function() {
                $(this.el).html(this.model.get('name') + "<button class='button'>"+"delete"+"</button>");
                return this;
            }
        });

        var view = new FriendListView({
            el: $('#friends'),
            collection: new FriendList()
        });
    });