Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait to render view in backbone.js until fetch is complete?

I'm trying to understand how a portion of backbone.js works. I have to fetch a collection of models once the app begins. I need to wait until fetch is complete to render each view. I'm not 100% sure the best approach to take in this instance.

var AppRouter = Backbone.Router.extend({     routes: {         "": "home",         "customer/:id": "customer"      },      home: function () {         console.log("Home");     },      customer: function (id) {         if (this.custromers == null)             this.init();          var customer = this.customers.at(2); //This is undefined until fetch is complete. Log always says undefined.         console.log(customer);     },      init: function () {         console.log("init");         this.customers = new CustomerCollection();         this.customers.fetch({             success: function () {                 console.log("success");                  // I need to be able to render view on success.             }         });         console.log(this.customers);     } });     
like image 887
Frankie Avatar asked Feb 12 '12 16:02

Frankie


People also ask

What are views in Backbone JS?

The Backbone. js Views specify how your data looks like. They represent model's data to the users. They can be used with any JavaScript template library.

What is the only method available in the backbone JS history?

There is only method named "start" can be used to manipulate the Backbone. js history.


1 Answers

The method I use is the jQuery complete callback like this:

var self = this; this.model.fetch().done(function(){   self.render(); }); 

This was recommended in a Backbone bug report. Although the bug report recommends using complete, that callback method has since been deprecated in favor of done.

like image 172
Rovanion Avatar answered Sep 21 '22 11:09

Rovanion