将函数句柄转换为jquery click事件函数的范围问题?

时间:2012-10-10 17:59:46

标签: javascript jquery

  

可能重复:
  Javascript Closure Problem

在以下代码中,TrueThis.aChoices[i]['CallBack']是创建click事件时的函数,而实际发生click事件时是“false”。如何将函数引用引入click事件处理程序?

我的对象:

ATK.MultiChoiceDialog = function() {

   var TrueThis = this;
   var aChoices;

   this.Show = function(sTitle,sPrompt,aChoices){
      this.aChoices = aChoices;

      var HTML = '[snip]';
      $('body').append(HTML);

      for(var i in this.aChoices)
      {      
         console.log(TrueThis.aChoices[i]['CallBack']); // shows "function"
         $('#ATKDialogButton'+i).click(function(e){
            console.log(TrueThis.aChoices[i]['CallBack']); // shows "false" ???
            if(TrueThis.aChoices[i]['CallBack'])
            {
               TrueThis.aChoices[i]['CallBack'].call(aChoices[i]['Context']);
            }
         });      
      }
   }
};

我也试过了:

for(var i in this.aChoices)
{      
   var CB = TrueThis.aChoices[i]['CallBack'];
   console.log(CB); // function
   $('#ATKDialogButton'+i).click(function(e){
      console.log(CB); // false
      if(TrueThis.aChoices[i]['CallBack'])
      {
         TrueThis.aChoices[i]['CallBack'].call(aChoices[i]['Context']);
      }
   });      
}

2 个答案:

答案 0 :(得分:1)

jQuery有一种内置的处理方法,它通过将事件数据传递给绑定到事件的回调函数。

ATK.MultiChoiceDialog = function() {

   var TrueThis = this;
   var aChoices;

   this.Show = function(sTitle,sPrompt,aChoices){
      this.aChoices = aChoices;

      var HTML = '[snip]';
      $('body').append(HTML);

      for(var i in this.aChoices){ // in js the '{' should be on same line
         console.log(TrueThis.aChoices[i]['CallBack']); // shows "function"
          $('#ATKDialogButton'+i).click({i:i},function(e){ // data passed in with {i:i}
            console.log(TrueThis.aChoices[e.data.i]['CallBack']); // shows "function" 
            if(TrueThis.aChoices[e.data.i]['CallBack']){ // in js the '{' should be on same line
               TrueThis.aChoices[e.data.i]['CallBack'].call(aChoices[e.data.i]['Context']);
            }
         });      
      }
   }
};​

答案 1 :(得分:0)

感谢您的评论,我有这个工作。首先创建一个新函数来“修复”i的值,它返回事件处理程序的函数。

this.FixI = function (i){
   return function(e){
      if(TrueThis.aChoices[i]['CallBack'])
      {
         TrueThis.aChoices[i]['CallBack'].call(TrueThis.aChoices[i]['Context']);
      }
   }
}

使用new函数在循环中生成偶数处理函数:

for(var i in this.aChoices)
{
   $('#ATKDialogButton'+i).click(TrueThis.FixI(i));      
}

更新:看起来Kevin B找到了一种解决问题的Jquery方法,不需要额外的“保存”功能。