2013-02-28 121 views
0

關於this question,我試圖添加一個回調來獲取數據。所以,我想這一點:Javascript中的遞歸異步回調

var subgroupIds = []; 
var that = this; 
this.getSubGroups = function (groupId,callback) { 
    var anotherObject = this; 
    this.getGroups("groupId="+groupId, function(groups) { 
     if ($.isEmptyObject(groups)) { 
      return; 
     } else { 
      $.each(groups, function(index,group) { 
       subgroupIds.push(group.id); 
       that.getSubGroups(group.id); 
      }); 
      anotherObject.callback(group.id); 
     } 
    }); 
} 

,我想我有以前的問題後更好地理解封閉的,但我想我不......,我發現了以下錯誤:

Uncaught TypeError: Object [object Window] has no method 'callback' 

我在這裏做錯了什麼?

編輯

這裏的getGroups的內容:

this.getGroups = function(filter,callback,error_callback) { 
    this.getJSON('/'+apiVersion+'/groups/',function(data){ 
     // run through the filter engine 
     output = runFilter(data, filter); 
     callback(output); 
    },error_callback); 
} 
+0

也許'this.getGroups'應該是'anotherObject.getGroups'? – 2013-02-28 14:34:09

+0

爲什麼使用'anotherObject'而不是'that'?爲什麼你回調一個屬性,你不想回調函數參數? – Bergi 2013-02-28 14:37:20

+0

什麼是'這個'''那個'?當你聲明'this.getSubGroups'時,'this'是指'window',所以你沒有做正確的事情來讓'this'指向正確的東西。然後,'anotherObject'就是指同一個'window'。另外,你爲什麼試圖使用'anotherObject.callback(group.id)'?你不只是想'回調(group.id);'? – Ian 2013-02-28 14:37:24

回答

1

它不必須anotherObject.callback(group.id);,你需要的是callback(group.id);

它看起來像你與arguments對象混淆this

arguments認爲,被傳遞到函數的所有參數:

var aFunction = function() { 
    for (var i = 0; i < arguments.length; i++) { 
     console.log(arguments[i]); 
    } 
}; 

aFunction(1, 2, 3, 4); // 1, 2, 3, 4 

雖然this基本上指的是功能的「所有者」(這是粗略地講,無論發生什麼事是點前):

var aFunction = function() { 
    console.log(this); 
}; 

var object1 = { f: aFunction, name: "object1" }; 
var object2 = { f: aFunction, name: "object2" }; 

object1.f(); // Object { name="object1", f=function()} 
object2.f(); // Object { name="object2", f=function()} 
aFunction(); // Window 
+0

我_think_我明白你在說什麼。由於'callback'是'getSubGroups'的一個參數,'getGroups'對'callback'沒有可見性,因爲它是另一個級別。我試着改變'anotherObject。callback(group.id);'''callback(group.id);'但是我得到了這個錯誤:'Uncaught TypeError:undefined不是函數' – PLui 2013-02-28 14:53:52

+0

@PLui這是因爲你遞歸調用'that.getSubGroups group.id);' - 你不提供第二個參數 - 回調 - 這就是爲什麼它是'未定義'的原因。您每次調用函數時都必須提供回調函數,或者引入一個檢查:'if(callback){callback(group.id); }' – 2013-02-28 14:55:16

+0

如果你想在每個遞歸調用中調用相同的回調,你只需要傳遞它:'that.getSubGroups(group.id,callback);' – 2013-02-28 15:08:52

0

回調是一個參數,它沒有被綁定到上下文。

我想你想要的是調用回調anotherObject作爲this的值,對吧?

可以實現與:

$.proxy(callback, anotherObject)(group.id); 

或者,如果你只是想執行回調,並且要使用閉合,您需要添加:

this.callback = callback; //before 
var anotherObject = this; 
+0

有了這個代理東西,你的意思是'callback.call(anotherobject,group.id)'? – Bergi 2013-02-28 14:48:41