Backbone js: load bootstrap data with jquery promises and deferred

Problem:

While working with front end frameworks such as Backbone.js, we need some initial data which might be coming from remote source.

  1. Best option is using a server side template, we can simply embed the JSON data needed to populate our initial models right in the page itself.
    var appInitialData = {{server_generated_json}};
    
    
  2. Go to Backbone way
  3. Sometimes we need to work with promises, so that we can start our application after getting required data.

Here is sample code, in this case i need data from 2 sources to bootstrap my module/app,

 

var App = App || {};

App = { 
    getAppData: function(){

      var self = this;

      var deferred = $.Deferred(),
      requests = [];

      requests.push( $.getJSON('request/ajax/url/1' ) );
      requests.push( $.getJSON('request/ajax/url/2' ) );

      $.when.apply(jQuery, requests).done(function(xhrResponse) {
        return deferred.resolve(xhrResponse.result);
      });

      return deferred;

    },
    init: function(){

        this.getAppData().done(_.bind(function(result) {
           //do the operations which you wanted to do when you get response from ajax
           //for example, i wants to start module
           this.boostrapApp();
        }, this));

    },
    boostrapApp: function(){
         //go for 
    },


 }; 
 App.init();

 

Advertisements

11 Comments

  1. I blog quite often and I seriously thank you for your
    information. Your article has truly peaked
    my interest. I’m going to book mark your website and keep checking for new details about once
    a week. I subscribed to your Feed as well.

    Like

  2. Very great post. I just came across your weblog and wished to state that I’ve really enjoyed browsing
    your weblog posts. In fact I’ll be subscribing on your rss feed
    and I’m hoping you write again immediately!

    Like

Comments are closed.