2013-04-23 19 views
1

我收到以下錯誤,當我按下提交鍵:未捕獲的ReferenceError。原型函數沒有jQuery的事件處理中發現

Uncaught ReferenceError: addText is not defined 
  • 怎麼來的「點擊」處理功能無法找到類函數原型「添加文字'?

  • 我能做些什麼來解決這個問題?

  • 如果這是處理事件的不好方法? (我來自一個Java的背景,我與面向對象的JavaScript的最佳做法有點不確定)

下面是代碼:

<head> 
    <title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <script src="js/jquery-1.9.1.js"></script> 
    <script> 
     //Class ctor 
     function MyClass() { 
      this.msg = "Hello World!"; 
     } 
     //This method appends text to the given doc element 
     MyClass.prototype.addText = function(doc) { 
      $(doc).append('<br/>'+this.msg); 
     }; 
     /* 
     * This method adds a 'click' listener to the given element which 
     * calls the 'addText' method on its parent. 
     */ 
     MyClass.prototype.listenToButton = function(btn) { 
      $(btn).bind({ 
       click: function(event) { 
        addText($(this).parent()); 
       } 
      }); 
     }; 

     $(document).ready(function() { 
      //Create instance of class 
      var c = new MyClass(); 
      //Listen to button 
      c.listenToButton($("#mybutton")); 
     }); 
    </script> 
</head> 
<body> 
    <div>Button: <input id="mybutton" type="button" value="Submit"></div> 
</body> 

顯然我使用jQuery。提前致謝!

編輯

這是我學到的:

  • 的「點擊」處理功能無法找到函數「addText」,因爲「這」不再引用的類的實例,但事件的發送者。

  • 要解決這個問題,我應該將當前'this'作用域保存在處理函數外部的變量中。

  • 我不確定以這種方式處理事件是否是不好的做法,但它起作用,所以我要去用它。

  • 此外,我應該使用'on'而不是'bind',因爲它看起來像'綁定'調用'反正'。

感謝大家的快速回復!

+0

您應該使用'on',而不是'bind'。你需要了解'this'的範圍。 – epascarello 2013-04-23 15:27:55

+1

基本上,在click事件中,上下文('this')不再是MyClass的實例,它是被單擊的元素*,因此addText沒有被定義。 – 2013-04-23 15:28:21

+0

@epascarello好的,有什麼區別? – souldzin 2013-04-23 15:28:54

回答

5

試試這個:

MyClass.prototype.listenToButton = function(btn) { 
     var that = this; 
     $(btn).bind({ 
      click: function(event) { 
       that.addText($(this).parent()); 
      } 
     }); 
    }; 
+0

這工作完美。感謝您的及時回覆!這是應該如何處理這些情況,還是這是一個糟糕的設計的症狀? – souldzin 2013-04-23 15:33:35

+2

@SoulDZIN這是一個典型的問題解決方案,另一種選擇是將'this'傳遞給使用iife的函數,或者通過'Function.bind'或'jQuery.proxy'控制上下文的內容。定義一個'''var'是處理它的正常方式。 – 2013-04-23 15:44:08

+0

@Kevin B好吧,很高興知道,謝謝! – souldzin 2013-04-23 15:46:20

相關問題