Re: [問題] JavaScript 的非同步物件導向寫法

看板Ajax作者 (大嘴先生)時間12年前 (2013/11/17 09:32), 編輯推噓2(207)
留言9則, 2人參與, 最新討論串2/2 (看更多)
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)

11/17 09:45, , 1F
感謝!! 不過 getA_Callback 有沒有辦法在外部html也弄成
11/17 09:45, 1F

11/17 09:45, , 2F
getA.done(???)的形式 ?
11/17 09:45, 2F

11/17 11:26, , 3F
可以啊 在外部就直接寫a.getDataA.done(...).fail(...)
11/17 11:26, 3F

11/17 22:40, , 4F
我測試只有getA的done有成功trigger, getB和init都沒有耶
11/17 22:40, 4F

11/17 22:41, , 5F
還有B取得的資料要用到A,所以$.when 會依照順序執行嗎
11/17 22:41, 5F

11/17 22:41, , 6F
還是會同時.. 如果同時就會有問題
11/17 22:41, 6F

11/18 08:55, , 7F
會同時 你要依順序的話就改用pipe吧
11/18 08:55, 7F

11/18 09:02, , 8F
懶得寫了 直接google jquery pipe在黑暗執行緒就有很
11/18 09:02, 8F

11/18 09:02, , 9F
好的範例了
11/18 09:02, 9F
文章代碼(AID): #1IY1ovlu (Ajax)
文章代碼(AID): #1IY1ovlu (Ajax)