otmezger
otmezger

Reputation: 10784

backbone - how to trigger render of view after fetching all models in a collection

I made a loop over the models in a collection to fetch with the function fetchAll within the collection description.

fetchAll: function(){
    this.counter=0;
    self = this;
      for (var i=0;i<this.models.length; i++){
      this.models[i].fetch({
        success: function(){
          self.counter +=1;
          if (self.counter == self.models.length){
            alert('done');
            self.doneFetchAll = true;
          }
        }
      });

      //console.log(i);
      }

After the fetching is done, I see an alert and the collection property doneFetchAll is set to true.... but how to trigger the render of the view after this has been done?

1) is there a possibility in backbone to listen to a change in a specific attribute of the collection and if positive, call the render again?

OR

2) is there a better approach to fetch all models in the collection and THEN re render the view?

all this efforts of listening to changes have failed (whiting the initialize: function() of the view):

this.listenTo(this.collection, "change:doneFetchAll", this.render);

or

this.collection.on("change:doneFetchAll", this.render, this);

thanks.

Upvotes: 0

Views: 1143

Answers (2)

gerl
gerl

Reputation: 1181

Cant you just listen to "sync" event instead of fetchAll?

this.listenTo(this.collection, "sync", this.render)?

Upvotes: 0

Rida BENHAMMANE
Rida BENHAMMANE

Reputation: 4129

Try to use a custom event :

fetchAll: function(){
    this.counter=0;
    self = this;
      for (var i=0;i<this.models.length; i++){
      this.models[i].fetch({
        success: function(){
          self.counter +=1;
          if (self.counter == self.models.length){
            self.trigger('fetchAll'); // here
            self.doneFetchAll = true;
          }
        }
      });

  //console.log(i);
  }

and then in the initialize: function() :

this.listenTo(this.collection, "fetchAll", this.render);

Upvotes: 1

Related Questions