souldzin
souldzin

Reputation: 1476

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 

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. Thanks in advance!

EDIT

Here's what I've learned:

Thanks everyone for your quick replies!

Upvotes: 1

Views: 2338

Answers (1)

vher2
vher2

Reputation: 990

Try this:

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

Upvotes: 5

Related Questions