作者mrbigmouth (大嘴先生)
看板Ajax
標題Re: [問題] JavaScript 的非同步物件導向寫法
時間Sun Nov 17 09:32:38 2013
function MyOJ(param) {
this.predata = param;
this.dataA = null;
this.dataB = null;
this.processA = null;
this.processB = null;
}
MyOJ.prototype =
{'init' :
function() {
return $.when(this.getDataA(), this.getDataB());
}
,'getDataA' :
function() {
return this.processA ||
(this.processA =
$.post(urlB)
.done( function(data) { this.dataA = data; })
.done( getA_Callback )
.fail( getA_Fail )
);
}
,'getDataB' :
function() {
return this.processB ||
(this.processB =
$.post(urlC)
.done( function(data) { this.dataB = data; })
.done( getB_Callback )
.fail( getB_Fail )
);
}
}
var a = new MyOJ(params);
a.init().done(function() {
$('#dataA').text(a.dataA); //保證有資料
$('#dataB').text(a.dataB); //保證有資料
})
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 1.34.192.129
※ 編輯: mrbigmouth 來自: 1.34.192.129 (11/17 09:33)
1F:推 Fonger:感謝!! 不過 getA_Callback 有沒有辦法在外部html也弄成 11/17 09:45
2F:→ Fonger:getA.done(???)的形式 ? 11/17 09:45
3F:→ mrbigmouth:可以啊 在外部就直接寫a.getDataA.done(...).fail(...) 11/17 11:26
4F:推 Fonger:我測試只有getA的done有成功trigger, getB和init都沒有耶 11/17 22:40
5F:→ Fonger:還有B取得的資料要用到A,所以$.when 會依照順序執行嗎 11/17 22:41
6F:→ Fonger:還是會同時.. 如果同時就會有問題 11/17 22:41
7F:→ mrbigmouth:會同時 你要依順序的話就改用pipe吧 11/18 08:55
8F:→ mrbigmouth:懶得寫了 直接google jquery pipe在黑暗執行緒就有很 11/18 09:02
9F:→ mrbigmouth:好的範例了 11/18 09:02