2016-03-17 36 views
-1

我有一個腳本可以加載額外的數據,併爲視圖的多個元素提供額外的功能。 我喜歡採取更多OPP aproach來做到這一點,所以我有「班」建立我的實體。我現在面臨的問題是,信息來自服務器端,所以我需要這些數據才能提供功能。如何在強制數據的ajax請求中使用promises?

在我的腳本中,我有三個對象 User,Prospect和ProspectDetailView。

所以我以這種方式工作。

$(document).ready(function _document_ready() 
{ 

//* 
ajaxStatus.showStatus('Cargando información adicional...'); 
var promotor  = new User(); 
var prospecto  = new Prospect($("input[name=record]").val()); 
var vistaDetalle = new ProspectDetailView(); 



vistaDetalle.drawAditionalStatusTag(prospecto.data); 
vistaDetalle.drawGroupDataField(prospecto.inscription); 
vistaDetalle.drawInscriptionDifferences(prospecto.data, prospecto.inscription); 
vistaDetalle.drawPendingRequestTag(prospecto.inscription.requests); 
vistaDetalle.drawPendingTicketTag(prospecto.inscription.tickets); 
vistaDetalle.drawTicketsHistoryPanel(prospecto.inscription.tickets_h); 

ajaxStatus.hideStatus(); 
//*/ 
});//#END _document_ready() 

正如你所看到的創建一個用戶然後一個前景並最終加載我的視圖對象。

問題是我需要來自潛在客戶的數據(必需)才能使用視圖。

我打開我的展望這樣

// Definiciones de la información del prospecto. 
var Prospect = function (uuid){ 
this.uuid = uuid; 

var __init__ = function (self) 
{ 
    $.ajax({ 
     type : "POST", 
     dataType: "json", 
     data : {"confirm" : true }, 
     "context": self, 
     "async" : false, 
     url  : dev()+'/crmutilidades/get_inscription_data/'+self.uuid+'/'+module_sugar_grp1, 
     success : function _success_get_inscription_data(response) 
     { 
      this.inscription = response.data; 
      this.data = response.data.prospect; 
      this.paid = response.data.inscrito !== 'undefined' ? response.data.inscrito : false; 
     } 
    }); 
} 
__init__(this); 

}//#END Prospect 

我需要使用異步假以獲取潛在客戶數據之前,我可以在視圖對象使用它,和它的作品,但不能停止感覺這是一個討厭的黑客或錯誤。

所以我試圖用$。當(許諾我猜的稱呼)

和這樣做:

prospect = null; 
    user = null; 
    $.when(prospect = new Prospect(), user = new User).then(function(){ 
    view = new ProspectDetailView(); 
    ...Do all view calls. 
}); 

希望當前景和用戶加載完成,但我不認爲將執行。 我得到同樣的錯誤。 前景未定,因爲一切都是異步的。

我該如何建模。據我可以告訴我需要直接將ajax調用傳遞給$ .when方法,但這將打敗讓我的實體相互分離和隔離的目的。

+0

*「但是不能阻止它是一個討厭的黑客或錯誤的感覺。」*偉大的,因爲它!下一步是確保你實際上有承諾與合作。 $ .ajax會返回一個,所以您應該將其作爲Prospect實例的一個屬性顯示,以便您可以在$ .when中使用它。 –

+0

我給你提供一個例子,我想你的意思是做一個名爲this.load = $ .ajax({})的屬性,然後明確地做$ .when(Prospect.load,user.load).then(stuff );我會嘗試,但我dónt喜歡明確調用負載的想法我雖然__init__類似方法的構造更好。 –

+0

你的'Prospect'和'__init__'函數不返回任何東西,所以沒有什麼承諾可以等待。然而,他們可能不應該,看看[是不是好的做法有一個構造函數返回一個承諾?](http://stackoverflow.com/a/24686979/1048572) – Bergi

回答

0

您可以使用Promise。

var prospect_created = new Promise(function(resolve, reject){ 
    // any necessary setup 
    $.ajax({ 
     success: resolve, 
     error: reject, 
     // etc 
    }) 
}) 

create_prospect.then(function(prospect){ 
// create your view using the prospect 
}) 

通過傳遞決心,成功參數到你的Ajax請求,無論是從Ajax請求返回的將是參數傳遞給承諾對象的.then方法的功能。

+0

'承諾',「本機」和「HTML5」沒有任何關係。 – Bergi

+0

不要使用'Promise'構造函數來創建ajax承諾,請參閱[這裏是關於如何正確地執行此操作](http://stackoverflow.com/a/31327725/1048572) – Bergi