View Full Version : Assigning events to form elements with a Javascript Class

03-28-2005, 03:57 AM
Hi All - I am relearning Javascript, and figured this time around I'd do it with a OOP and DOM approach. Here is the first problem I have encountered. I have a Javascript class that creates some form elements on a page. I am trying to assign events from a button to handlers within the class. Something like this:

//parentBlock: a html element to draw the button into
function MyClass(parentBlock) {
//establish class properties
this.parentBlock = parentBlock;
this.animal = 'Kangaroo';

//create a new button
var btnElement = document.createElement('input');
btnElement.setAttribute('type', 'button');
btnElement.setAttribute('value', 'Test');
var btn = this.parentBlock.appendChild(btnElement);

//assign click event to trigger method in the class
btn.onclick = this.testMethod;

MyClass.prototype.testMethod = function() {

window.onload = function() {
new MyClass(document.getElementById('myForm'));

testMethod gets invoked fine when the button is pressed, but this points to the button, rather than the object instance. So when I do the alert in testMethod i am getting undefined rather than 'Kangaroo' as I would expect. Can anyone tell me what I am doing wrong? The problem would seem to be in the last line of the constructor. Is my OOP methodology way off - and I should be approaching this problem in a different manner? I have also tried eventListeners - but the result is the same.

Harry Armadillo
03-28-2005, 04:34 AM
Insert self=this; into MyClass; use self.animal in testMethod.

03-28-2005, 05:45 AM
Thanks Harry - I've tried a few variations on that; assigning this to a variable. But it isn't working for me. I'm sure I've overlooked something.

03-28-2005, 06:13 AM
Actually - assigning this to variable in the way you suggest (without var), makes the variable global - right? And in doing so, is useless to me. For example, say I create 5 instances of MyClass - then self is always going to point to the most recent object?

04-03-2005, 03:53 PM
Not if you use the var keyword. Then it'll be local.