user896715
user896715

Reputation: 109

Backbone render before fetch

I am using the backbone LayoutManager to manage my views.

I am having an issue fetching the model data before render is called, which obviously throws an error since the Ajax success callback is not done yet.

One way to fix this would be to fetch the model within the router and put app.useLayout("main").render(); into the success method. Is that the right way to do it or is there a better solution?

Router code :

app.useLayout("main").setViews({
    ".place-detail": new Place.Views.Show({
      model: new Place.Model({ place_id: place_id })
    })
}); 

app.useLayout("main").render();

View code :

Views.Show = Backbone.View.extend({
    initialize: function(options) {
        _.bindAll(this,"render");
        this.model.on("change", this.render, this);
        this.model.fetch();
    });
});

Upvotes: 0

Views: 914

Answers (1)

Matt
Matt

Reputation: 76

Backbone's fetch accepts success and error callbacks, so if you want to wait for the fetching to finish before executing more code, put it in the success callback:

Views.Show = Backbone.View.extend({
    initialize: function(options) {
        var _this = this;
        _.bindAll(this,"render");
        this.model.fetch({
          success: function(model, response) {
              _this.render();
              _this.model.on("change", _this.render, _this);
              _this.someOutsideFunctionCall();
          },
          error: function(model, response) {
              console.log("Error Fetching.");
          }
        });
    };
});

I've been coding a lot in CoffeeScript so I'm not sure if I got all the ({});s correct, but that's the basic gist of it. Note the declaration of _this = this, since if you try to reference this inside the callback function, it won't know what you're talking about.

Upvotes: 2

Related Questions