2012-08-09 161 views
2

我有一个简单的jQuery ready事件,它通过调用setupView对象中的函数来初始化视图。如何从内部嵌套函数调用父函数?

我的问题是,如何从init函数调用功能setSomethingImportant的适当方式如下所示?

由于呼叫是从与init函数不同的执行上下文中进行的,因此this.setSomethingImportant()不起作用。但是,如果我使用setupView.setSomethingImportant(),它就可以工作。我遇到的问题是,如果var名称(setupView)发生更改,我将不得不更改代码的主体。

(function() {   
     $(document).ready(function() {    
      setupView.init();    
     });  
     var setupView = {   
      currentState : "CT",    
      init : function() { 
       $("#externalProtocol").change(function() { 
        console.log("Changed =" + $(this).val()); 
        setSomethingImportant(); 
           // Question ? how to call a method in the setupView object 
       });   
      },   
      setSomethingImportant : function() { 
       this.currentState="TC";  
       console.log("Something has changed :" + this.currentState); 
      }  
     } 
}(jQuery); 

回答

3

商店this到一个变量:

var setupView = { 
    currentState: "CT", 
    init: function() { 
     // Keep a reference to 'this' 
     var self = this; 
     $("#externalProtocol").change(function() { 
      console.log("Changed =" + $(this).val()); 

      // Use the old 'this' 
      self.setSomethingImportant(); 
     }); 
    }, 
    setSomethingImportant: function() { 
     this.currentState = "TC"; 
     console.log("Something has changed :" + this.currentState); 
    } 
}; 

Working demo

+0

谢谢@Florent。说实话,我一直在使用你建议的方法。但我不确定是否将“this”存储在变量中是最佳做法。 – Rocky 2012-08-09 16:23:39

+0

有时你没有选择。你使用这个_trick_的次数越少,你的代码越干净。 – Florent 2012-08-09 16:25:09

1

只是单独声明函数,然后调用,像这样:

function setSomethingImportant(context) { 
    context.currentState="TC";  
    console.log("Something has changed :" + context.currentState); 
}; 

(function() {   
     $(document).ready(function() {    
      setupView.init();    
     });  
     var setupView = {   
      currentState : "CT",    
      init : function() { 
       $("#externalProtocol").change(function() { 
        console.log("Changed =" + $(this).val()); 
        setSomethingImportant(this); 
           // Question ? how to call a method in the setupView object 
       });   
      },   
      setSomethingImportant : function() { 
       setSomethingImportant(this); 
      }  
     } 
}(jQuery); 
+0

您仍然在'change'处理程序中传递了错误的上下文。 – 2012-08-09 16:11:18

1

请注意,我更改了我原来的解决方案。我现在使用even.data将数据传递给事件处理程序。

(function() {   
    $(document).ready(function() {    
     setupView.init();    
    });  
    var setupView = {   
     currentState : "CT",    
     init : function() { 
      $("#externalProtocol").change({ _this: this }, function (event) { 
       console.log("Changed =" + $(this).val()); 
       event.data._this.setSomethingImportant(); 
      });   
     },   
     setSomethingImportant : function() { 
      this.currentState="TC";  
      console.log("Something has changed :" + this.currentState); 
     }  
    } 
}(jQuery);