Search code examples
javascriptjquerybackbone.js

How Can I Reset This Backbone View on Collection Change?


How can I bind this view to collection change events so that it Resets when a new item has been added to the collection?

KAC.Views.ModuleMainNavigation = Backbone.View.extend(
    {
        tagName: "div",
        id: "",
        className: "",
        template: JST['modules/main_navigation'],
        initialize: function() {
            _.bindAll(this);
        },
        events: {
        },
        render: function () {
            this.$el.html(
                this.template(
                    { 
                        collection : this.collection 
                    }
                )
            );

            return this;
        }
    }
);

Solution

  • You have to listen for the change event.
    Most of the time this is done in the initialize function.

    You could either listen for all events (model change, collection reset, new model, model removed):

    this.collection.on('change reset add remove', this.render, this);
    

    Or only for the new model added event:

    this.collection.on('add', this.render, this);
    

    See also backbone.js collection events