我正在嘗試制定正確的模式以用於使用AJAX調用進行初始化的單身人士。這是我已經工作的一個簡單例子。帶AJAX初始化程序設計模式的javascriptMVC單身人士
它按預期工作,但我有一種感覺,這不是「正確的」方式,並且有一些方法可以將初始化程序的回調掛接到當前運行的ajax請求的成功調用中,而且我擔心那裏可能是陣列方法的競爭條件。我在正確的軌道上嗎?
var singletonObj;
$.Class("SingletonTest", {
init: function(onSuccess) {
if (singletonObj) {
if (singletonObj.ajaxLoaded) {
onSuccess(singletonObj);
}
else {
singletonObj.callbacks.push(onSuccess);
}
}
else {
singletonObj = this;
singletonObj.callbacks = new Array(onSuccess);
singletonObj.count=0;
$.ajax({
url: "/path/to/json/config",
method: "GET",
success: function (res) {
singletonObj.data = res.meta_data;
singletonObj.ajaxLoaded = true
singletonObj.callbacks.forEach(function(callback) {
callback(singletonObj);
});
}
});
}
},
counter: function() {
return this.count++;
}
});
new SingletonTest(function(obj) { console.log("First call: "+obj.counter()) });
new SingletonTest(function(obj) { console.log("Second call: "+obj.counter()) });
new SingletonTest(function(obj) { console.log("Third call: "+obj.counter()) });
還是有更簡單的方法來做到這一點?我在這裏想念什麼概念會讓生活變得更輕鬆?
可以站在提高評論的相關性! – cliveholloway
此外,forEach不會在IE中工作,應避免使用新的Array()(改爲編寫[onSuccess])。 – noah