2010-03-29 61 views
0

我得有一个方法,我可以添加回调的原型:(请忽略data_arg =真正的,因为它是不相关的其他部分)奇怪的递归无限循环,我不能追查

/* 
* 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; 
    } 
}; 

在我的具体情况下,我添加了三个回调函数。如果最后为元素调用this.data_callback(),则会导致整个事物循环无限。 在我试图跟踪bug了,上面的警报(是的,我知道有是为调试工具,但它是方式更舒服像)提供以下洞察问题:

  1. 的匿名函数/闭包(包含jQuery.extend()的函数)被调用。 new_callback包含第三个回调函数。 old_callback包含另一个...
  2. 被调用的匿名函数。 new_callback包含第二个回调函数。 old_callback应该包含第一个回调函数,但实际上它是另一个...
  3. 匿名回调被调用。 new_callback再次包含第二个回调函数。 old_callback包含匿名函数
  4. ...

现在,我错过?这是一些奇怪的关闭魔法还是我显然无法看到的一些明显的错误?

在此先感谢!

回答

2

为什么old_callback定义为var

var old_callback = this.data_callback; 

事实上,这是一个全局变量。也许它是在其他地方宣布的,但它对我仍然看起来很可疑。

+0

通过使用'this'关键字判断,发布的代码看起来像是类的一部分,而old_callback可能是该类的私有属性。 – 2010-03-29 13:52:46

+0

Awwwww。 @安迪:事实并非如此。 – balu 2010-03-29 13:55:04

+0

@codethief:继续;-) @Pointy:+1。 – 2010-03-29 14:27:04