作者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