我有一个原型,有一个方法可以添加回调:
/*
* Add a callback function that is invoked on every element submitted and must return a data object.
* May be used as well for transmitting static data.
*
* The callback function is supposed to expect a jQuery element as single parameter
* and must return a data object (for additional data to be sent along with the one already given upon initialization).
* Adding multiple callback functions results in those functions being invoked in the same order as they were added.
*
* 1) Therefore subsequent assignments to the same key in the data array override those that were performed by a previous callback function.
* 2) If data_arg = true is given, the data returned by the callback function that was previously called is given to the new_callback as 2nd argument, so it can be manipulated.
* However, even if it isn't, the unchanged data must be returned anyway to have any effect.
*/
this.add_data_callback = function(new_callback, data_arg) {
if(this.data_callback) {
old_callback = this.data_callback;
if(!data_arg) {
//alert('add it');
//alert(old_callback);
//alert(new_callback);
this.data_callback = function(element) {
//alert('do it');
//alert(old_callback);
//alert(new_callback);
return jQuery.extend(old_callback(element), new_callback(element));
};
}
else {
this.data_callback = function(element, data) {
return new_callback(element, old_callback(element));
};
}
}
else {
//alert('add the first');
//alert(new_callback);
this.data_callback = new_callback;
}
};
(请忽略data_arg = true的else部分,因为它不相关。)
在我的具体案例中,我正在添加三个回调函数。但是,如果最终为元素调用this.data_callback(),则会导致整个事件无限循环。 在我尝试跟踪错误时,上面的警报(是的,我知道有调试工具,但这样更舒服)提供了以下对此问题的见解:
现在,我想念什么?这是一些奇怪的封闭魔法还是一些我显然无法看到的明显错误?
提前致谢!
答案 0 :(得分:2)
为什么old_callback
未定义var
?
var old_callback = this.data_callback;
实际上,它是一个全局变量。也许它在其他地方宣布,但它仍然看起来很可疑。