简体   繁体   English

未捕获ReferenceError。 在jQuery事件处理程序中找不到原型函数

[英]Uncaught ReferenceError. Prototype function is not found inside jQuery event handler

I am getting the following error when I press the submit button: 按提交按钮时出现以下错误:

Uncaught ReferenceError: addText is not defined 
  • How come the 'click' handling function can not find the class prototype function 'addText'? 为什么“单击”处理函数找不到类原型函数“ addText”?

  • What can I do to fix this? 我该怎么做才能解决此问题?

  • If this a bad way of handling events? 如果这是处理事件的不好方法? (I come from a java background, and I'm a little unsure of the best practices with object oriented javascript) (我来自Java背景,对于面向对象的javascript的最佳做法我有点不确定)

Here is the code: 这是代码:

<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>

Obviously I am using jQuery. 显然我正在使用jQuery。 Thanks in advance! 提前致谢!

EDIT 编辑

Here's what I've learned: 这是我所学到的:

  • The 'click' handling function can not find the function 'addText' because 'this' no longer references the class instance but the sender of the event. “单击”处理函数找不到函数“ addText”,因为“此”不再引用类实例,而是事件的发送者。

  • To work around this, I should save the current 'this' scope in a variable outside the handler function. 要解决此问题,我应该将当前“ this”范围保存在处理程序函数外部的变量中。

  • I'm not sure if handling events this way is bad practice or not, but it works so I'm going with it. 我不确定以这种方式处理事件是否是不好的做法,但是它可以正常工作,所以我会继续使用它。

  • Also, I should use 'on' instead of 'bind' since it seems like 'bind' calls 'on' anyways. 另外,我应该使用“ on”而不是“ bind”,因为似乎“ bind”仍然会调用“ on”。

Thanks everyone for your quick replies! 感谢大家的快速回复!

Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM