2013-05-17 21 views
0

我使用jQuery的每個函數循環參數。以及我推動從「get」方法到數組的所有數據。一旦我的陣列已準備就緒,我需要調用一個函數骨幹..當和應用功能(jQuery)不能正常工作

做我這樣做:

var temps = []; 

     $.each(views,function(i,view){ 
      $.get("js/temp/" + view + ".html", function(data){ 
        temps.push(data); 
        console.log(temps); //results correctly. 
      }) 
     }) 

     $.when.apply(null,temps).done(function(){ 
      console.log(temps); //results as undefined 
     }); 

,但我得到的結果爲「未定義」 ..這裏有什麼問題。有人找我嗎?

進一步增加的問題,使用的答案我做到了..

$.each(views,function(i,view){ 
     var d = $.Deferred(); 
     requests.push(d.promise()); 
     $.get("js/temp/" + view + ".html", function(data){ 
       view.prototype.template = _.template(data);//not working when i use the string parameter.. 
       appView.prototype.template = _.template(data); //it works 
       temps.push(data); 
       d.resolve(); 
     }) 
    }) 

如何將字符串參數轉換爲返回功能..?

回答

2

你需要另一套延遲對象來處理這個問題:

var temps = []; 
    var requests = []; 

    $.each(views,function(i,view){ 
     var d = $.Deferred(); 
     requests.push(d.promise()); 
     $.get("js/temp/" + view + ".html", function(data){ 
       temps.push(data); 
       console.log(temps); //results correctly. 

       d.resolve(); 
     }) 
    }) 

    $.when.apply(null,requests).done(function(){ 
     console.log(temps); //results as undefined 
    }); 

使用AJAX deferreds:

var requests = []; 

    $.each(views,function(i,view){ 
     var d = $.get("js/temp/" + view + ".html"); 
     requests.push(d); 
    }) 

    $.when.apply(null,requests).done(function(){ 
     console.log(arguments); //results as undefined 
    }); 
+0

是的,它工作正常。但是沒有縮短的方法來做到這一點? – 3gwebtrain

+0

其實$ .get也會返回延遲對象,但是如果你需要首先從所有響應中收集數據,這是一個最佳方式 – claustrofob

+0

我現在正在接受另一個問題..實際上使用參數字符串,我需要一個函數,並且需要分配原型..如何將字符串轉換爲對象..?我更新了這個問題。 – 3gwebtrain

0

您只填充temps數組請求完成。當您撥打$.when()時,該數組仍然爲空。

相反,你需要創建一個未完成的AJAX請求的承諾數組:

var temps = views.map(function() { 
    return $.get("js/temp/" + view + ".html"); 
}); 
+0

但我想使用每種方法來迭代多個參數,我的想法是分配模板給eac h骨幹的看法。 – 3gwebtrain

+0

@ 3gwebtrain:我不知道你的意思。 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map。如果你不能使用'map()',你可以將promise傳遞給數組。 – SLaks