Add Collection

by agorur

HTML

<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<header>
        <h1>Showing views from a collection and basic events</h1>
        <p>The list below is made from JSON, passed to the view as a collection and has basic events</p>
    </header>

    <article>

    </article>

JavaScript

window.App = {

    Controller: {},
    Model: {},
    Collection: {},
    View: {},

    initialize: function() {

        var collection = new App.Collection.Inputs([
            {title: "Books"},
            {title: "Pens"},
            {title: "Gadgets"}
        ]);

        var view = new App.View.InputSet({
            collection: collection});
        
        $('article').html(view.render().el);
    }
}

App.Collection.Inputs = Backbone.Collection.extend();

App.View._input = Backbone.View.extend({

    events: {
        "click a": "close"
    },

    initialize: function() {
        _.bindAll(this, "render", "close");
    },

    render: function() {
        $(this.el).html(_.template('<p><%=title%> <a href="#">[close]</a></p>', this.model.toJSON()));
        return this;
    },

    close: function() {
        $(this.el).fadeOut(300);
        return false;
    }

});

App.View.InputSet = Backbone.View.extend({
    events: {
        'click a': 'clear'
    },
    initialize: function() {
        // this makes the render, clear etc available at this
        // if not setting this, both render() and clear() method will not have themselves in this
        _.bindAll(this, "render");
        
        this.collection.bind("add", this.addInput);
    },
    
    addInput: function(model) {
         var view = new App.View._Input({
                model: model
        });
        $(this.el).append(view.render().el);
    }
    // backbone required method, which renders the UI
    render: function() {

        var that = this;

        $(that.el).append('<a href="#">[clear]</a>');

        return this;
    },
    clear: function() {
        $(this.el).find('p').fadeOut(300);
    }
});


// wait for the dom to load
$(document).ready(function() {
    // this isn't backbone. this is running our earlier defined initialize in App
    App.initialize();
});