Search code examples
javascriptjqueryrequireamddeferred

RequireJS, $.Deferred how to?


Following is the code

define(['jquery'], function ($) {
  var App = function () {
    var settings = {};
    var identity = {};

    var dSettings = $.when($.getJSON("models/settings.json"));
    var dIdentity = $.when($.getJSON("models/identity.json"));

    var dApp = $.when(dSettings, dIdentity);

    dSettings.done(function (data) {
      settings = data;
      console.log(settings);
    });

    dIdentity.done(function (data) {
      identity = data;
    });

    return {
      "settings" : settings,
      "identity" : identity
    };
  };
  return App();
});

I want to create a module, who can "know" my settings and identity. Return will do before Deferred objects is resolved and module App.js have empty Settings and Identity objects.

How can I do that?


Solution

  • From what I can get, you want the module to fetch your settings and identity data and return it as an AMD module. Unfortunately, you have an asynchronous operation there. The best you could do is to return a promise from the module instead and let the depending modules attach then.

    // SettingsAndIdentity.js
    define(['jquery'], function ($) {
      // $.when resolves when all promises passed resolves
      return $.when($.getJSON("models/settings.json"), $.getJSON("models/identity.json"))
    });
    
    // foo.js
    define(['SettingsAndIdentity'], function(SettingsAndIdentity){
      // Since SettingsAndIdentity is a promise, we just attach then
      SettingsAndIdentity.then(function(settings, identity){
        // start doing things here
      });
    });