Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 290
ctrlShiftBryan Avatar asked Jan 05 '12 13:01

ctrlShiftBryan


1 Answers

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);
like image 93
kubetz Avatar answered Oct 04 '22 11:10

kubetz