1
我有一些方法(methA
,methB
...)需要在Javascript中調用相同的方法methMain
。這種方法methMain
然後需要獲取一些數據,當它完成後,對調用它的方法(methA或MethB ...)進行回調。創建一個參數使用相同的範圍參數 - 在Javascript中
我可以成功地創建使用什麼這裏寫指針/引用的方法:How can I pass a reference to a function, with parameters?
該解決方案,我已經看到了所有其他人,似乎並沒有在當前範圍內工作。 此代碼將無法正常工作:
function TestStructure() {
this.gotData = false;
//define functions
this.methA = function (parA) { };
this.methB = function (parb) { };
this.createFunctionPointer = function (func) { };
this.createFunctionPointer = function (func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
};
this.methA = function (parA) {
alert('gotData: ' + this.gotData + ', parA: ' + parA);
if (this.gotData == false) {
var fp = this.createFunctionPointer(this.methA, parA);
this.methMain(fp);
return;
}
//...do stuff with data
}
this.methB = function (parB) {
alert('gotData: ' + this.gotData + ', parB: ' + parB);
if (this.gotData == false) {
var fp = this.createFunctionPointer(this.methB, parB);
this.methMain(fp);
return;
}
//...do stuff with data
}
this.methMain = function (func) {
//...get some data with ajax
this.gotData = true;
//callback to function passed in as parameter
func();
}
}
var t = new TestStructure();
t.methA('test');
當methMain
做一個回調FUNC(methA
或methB
)變量this.gotData
將不會被設置。
有沒有針對這個問題的解決方案,還是我需要重新考慮設計? 我想要做到這一點,使用ajax獲取數據,而不使用async:false進行阻塞。
謝謝你的意見,它現在可以工作 - 這有點令人尷尬,因爲我嘗試了你在發佈之前做過的事情。 :-) – AxAn