Javascript中的递归异步回调
关于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);
}
它不必须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
我_think_我明白你在说什么。由于'callback'是'getSubGroups'的一个参数,'getGroups'对'callback'没有可见性,因为它是另一个级别。我试着改变'anotherObject。callback(group.id);'''callback(group.id);'但是我得到了这个错误:'Uncaught TypeError:undefined不是函数' – PLui 2013-02-28 14:53:52
@PLui这是因为你递归调用'that.getSubGroups group.id);' - 你不提供第二个参数 - 回调 - 这就是为什么它是'未定义'的原因。您每次调用函数时都必须提供回调函数,或者引入一个检查:'if(callback){callback(group.id); }' – 2013-02-28 14:55:16
如果你想在每个递归调用中调用相同的回调,你只需要传递它:'that.getSubGroups(group.id,callback);' – 2013-02-28 15:08:52
回调是一个参数,它没有被绑定到上下文。
我想你想要的是调用回调anotherObject
作为this
的值,对吧?
可以实现与:
$.proxy(callback, anotherObject)(group.id);
或者,如果你只是想执行回调,并且要使用闭合,您需要添加:
this.callback = callback; //before
var anotherObject = this;
有了这个代理东西,你的意思是'callback.call(anotherobject,group.id)'? – Bergi 2013-02-28 14:48:41
也许'this.getGroups'应该是'anotherObject.getGroups'? – 2013-02-28 14:34:09
为什么使用'anotherObject'而不是'that'?为什么你回调一个属性,你不想回调函数参数? – Bergi 2013-02-28 14:37:20
什么是'这个'''那个'?当你声明'this.getSubGroups'时,'this'是指'window',所以你没有做正确的事情来让'this'指向正确的东西。然后,'anotherObject'就是指同一个'window'。另外,你为什么试图使用'anotherObject.callback(group.id)'?你不只是想'回调(group.id);'? – Ian 2013-02-28 14:37:24