Vikram
Vikram

Reputation: 4190

Backbone.js reinstantiating collection does not update corresponding view

Here is my Model View and Collection :

window.Report = Backbone.Model.extend({});
window.ReportCollection = Backbone.Collection.extend({
   model: Report,     

   initialize: function(properties){
       this.url = properties.url;
   }
});

window.ReportCollectionView = Backbone.View.extend({
     initialize: function(){                   
        this.collection.reset();
        this.render();            
    },

    render: function(){
        var self = this;

        this.collection.fetch({

            success: function(){
                    self.collection.each(function(model){
                    //pass model to subview  
                    });
                }
            }
        });    

    }
});

in the other part of the code I use the instantiate the above objects

   var reportCollection = new ReportCollection({url:someURL});
   var reportCollectionView = new ReportCollectionView({collection:reportCollection});

'someURL' is a REST based URL that returns JSON list of Objects

So far everything looks good. What I am trying to achieve is: I must be able to refresh the 'reportCollection' by changing the url and this should trigger an updated 'reportCollectionView'. Thanks for any pointers

Upvotes: 1

Views: 385

Answers (1)

mu is too short
mu is too short

Reputation: 434585

I suppose you could add a method to your collection which changes url and forces a fetch:

window.ReportCollection = Backbone.Collection.extend({
    //...
    changeUrl: function(url) {
        this.url = url;
        this.fetch();
    }
});

and then bind to the "reset" event in your view:

window.ReportCollectionView = Backbone.View.extend({
    initialize: function() {
        _.bindAll(this, 'render');
        this.collection.on('reset', this.render);
        this.collection.reset();
    },
    //...
});

Then if you do this:

c = new ReportCollection(...);
v = new ReportCollectionView({ collection: c, ... });

You'll get your rendered view and then later you can:

c.changeUrl(...);

to set the new URL and that will trigger a render call on v.

Upvotes: 2

Related Questions