更新的代碼庫一個註釋:
有創建對象的雙向。
如果你需要創建對象的多個時間你會做這樣的:
var YourDefintinon = function() {
};
YourDefintinon.prototype.foo = function() {
};
obj1 = new YourDefintinon();
obj2 = new YourDefintinon();
obj1.foo();
如果你只需要一次在你的代碼你可以那樣做:
var obj = {
};
obj.foo = function() {
};
foo();
所以,你將需要main
只有一次你的代碼應該是這樣的:
使用Function.prototype.bind(及其polyfill舊版本瀏覽器),以將showUpdates
綁定到obj
。
var main = {
last_updated : null
};
function showUpdates(data){
this.last_updated = data.update_time;
}
main.updateMain = function() {
//<< bind showUpdates to `this` and save the bound function in the local variabel showUpdates
var showUpdates = showUpdates.bind(this);
$.ajax({
url:"/my_url/"
type:"POST",
datatype:"json",
data: {'last_updated':last_updated },
success : showUpdates, //<< uses the showUpdates variable not the function
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
},
});
};
當你不想讓showUpdates
訪問別人,你可以整個塊包裝成一個被稱爲立刻功能:
var main = (function() {
var main = {
last_updated : null
};
function showUpdates(data){
this.last_updated = data.update_time;
}
main.updateMain = function() {
var showUpdates = showUpdates.bind(this);
$.ajax({
url:"/my_url/"
type:"POST",
datatype:"json",
data: {'last_updated':last_updated },
success : showUpdates,
error : function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
},
});
};
return main;
}());
甚至_pseudo code_你應該確保它是清潔。是'main'真的周邊'showUpdates'和'updateMain',爲什麼你寫的'VAR this.main_updated',是'this.updateMain'一個函數,my_main_function'的'部分,如果叫意願的'ajax'請求? –
我將更改var名稱以使其更清晰 - 您將看到updateMain調用傳遞給服務器的更新函數上次更新的時間戳。 – user3467349
你對''有什麼意思,但是不需要多個main()'?你只有一個_main_對象,你不會再做一個'new main'?如果是這樣,你根本不需要'new main()'。 –