以下を考えると:
var doThings = (function ($, window, document) {
var someScopedVariable = undefined,
methods,
_status;
methods = {
init: function () {
_status.getStatus.call(this);
// Do something with the 'someScopedVariable'
}
};
// Local method
_status = {
getStatus: function () {
// Runs a webservice call to populate the 'someScopedVariable'
if (someScopedVariable === undefined) {
_status.setStatus.call(this);
}
return someScopedVariable;
},
setStatus: function () {
$.ajax({
url: "someWebservice",
success: function(results){
someScopedVariable = results;
}
});
}
};
return methods;
} (jQuery, window, document));
someScopedVariable
問題は明らかです。これは非同期の状況であり、未定義でなくなるまで待ってから続行したいと考えています。
jQuery の .when() -> .done() 遅延呼び出しを使用することを考えましたが、うまく動作しないようです。また、まだ定義されているかどうかを確認するだけのループを実行することも考えましたが、それはエレガントに見えません。
可能なオプション 1:
$.when(_status.getStatus.call(this)).done(function () {
return someScopedVariable;
});
可能なオプション 2 (ひどいオプション):
_status.getStatus.call(this)
var i = 0;
do {
i++;
} while (formStatusObject !== undefined);
return formStatusObject;
更新: 説明するためにあまりにも多くのロジックを削除したと思われるため、一部を追加し直しました。これの目標は、このデータへのアクセサーを作成することでした。