Backbone.js: How do I force the View to automatically refresh when changing a models collection

ctrlShiftBryan picture ctrlShiftBryan · Jan 5, 2012 · Viewed 13.2k times · Source

So I have a View that looks like this.

    //base class
    var SelectListView = Backbone.View.extend({
        initialize: function() {
            _.bindAll(this, 'addOne', 'addAll');
            this.collection.bind('reset', this.addAll);
        },
        addAll: function() {
            this.collection.each(this.addOne);
        },
        events: {
            "change": "changedSelected"
        },
        changedSelected: function() {
            this.selected = $(this.el);
            this.setSelectedId($(this.el).val());
        }

    });

    //my extended view
    var PricingSelectListView = SelectListView.extend({
        addOne: function(item) {
            $(this.el).append(new PricingView({ model: item }).render().el);
        }         
    });

I have instantiated the view like this...

var products = new ProductPricings();
var pricingsView = new PricingSelectListView({
     el: $("#sel-product"),
     collection: products
});

Somewhere else (another views custom method)I have updated the pricing view's collection

pricingsView.collection = new ProductPricings(filtered);

This does not seen to do anything.

pricingsView.render();

So now the collection has fewer items but the new view is never rendered or refreshed in the DOM.

How to I do I 1.) refresh the rendering in the DOM? 2.) Make it automatically refresh the DOM? Do I have to somehow tell it to render when ever the collection changes?

Answer

kubetz picture kubetz · Jan 5, 2012

You bound addOne() to a reset event. When you just replace the pricingsView.collection instance then that event is not triggered and addOne() is not executed.

Try instead:

pricingsView.collection.reset(filtered);