以下是代码
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();
});
我想创建一个模块,该模块可以“知道”我的设置和身份。
返回将在解析延迟对象并且模块App.js具有空的Settings和Identity对象之前执行。
我怎样才能做到这一点?
最佳答案
据我所知,您希望该模块获取您的设置和身份数据,并将其作为AMD模块返回。不幸的是,您在那里有一个异步操作。最好的办法是从模块返回一个Promise,并让依赖的模块附加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
});
});
关于javascript - RequireJS,$。推迟怎么办?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29808394/