Reputation: 1476
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'?
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)
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:
The 'click' handling function can not find the function 'addText' because 'this' no longer references the class instance but the sender of the event.
To work around this, I should save the current 'this' scope in a variable outside the handler function.
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.
Thanks everyone for your quick replies!
Upvotes: 1
Views: 2338
Reputation: 990
Try this:
MyClass.prototype.listenToButton = function(btn) {
var that = this;
$(btn).bind({
click: function(event) {
that.addText($(this).parent());
}
});
};
Upvotes: 5