tags:

views:

1306

answers:

3

Hi,

Is there a best-practice or common way in Javascript to have class members as event handlers?

Consider the following simple example:

<head>
    <script language="javascript" type="text/javascript">

        ClickCounter = function(buttonId) {
            this._clickCount = 0;
            document.getElementById(buttonId).onclick = this.buttonClicked;
        }

        ClickCounter.prototype = {
            buttonClicked: function() {
                this._clickCount++;
                alert('the button was clicked ' + this._clickCount + ' times');
            }
        }

    </script>
</head>
<body>
    <input type="button" id="btn1" value="Click me" />
    <script language="javascript" type="text/javascript">
        var btn1counter = new ClickCounter('btn1');
    </script>
</body>

The event handler buttonClicked get called, but the _clickCount member is inaccessible, or this points to some other object.

Any good tips/articles/resources about this kind of problems?

Best regards, JacobE

+6  A: 
ClickCounter = function(buttonId) {
    this._clickCount = 0;
    var that = this;
    document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}

ClickCounter.prototype = {
    buttonClicked: function() {
        this._clickCount++;
        alert('the button was clicked ' + this._clickCount + ' times');
    }
}
pawel
Thanks for your solution.I am also trying to understand the bigger picture - patterns, practices etc. Any good articles you know about?
JacobE
this thing is great: http://ejohn.org/apps/learn/
pawel
This is a good example, but this answer might be better with some explanation as to why it's a good solution, for the novices around here.
Sam Murray-Sutton
+1 woot (I said woot!)
blu
+1  A: 

It's a scoping issue - functions aren't in any way bound to the object which contains them, so you need to set up your event handlers in such a way that they have the appropriate execution context object when they're executed.

http://www.digital-web.com/articles/scope_in_javascript/

This question has some answers which will be of interest to you:

http://stackoverflow.com/questions/133973/how-does-this-keyword-work-within-a-javascript-object-literal

insin
+1  A: 

A function attached directly to the onclick property will have the execution context's this property pointing at the element.

When you need to an element event to run against a specific instance of an object (a la a delegate in .NET) then you'll need a closure:-

function MyClass() {this.count = 0;}
MyClass.prototype.onclickHandler = function(target)
{
   // use target when you need values from the object that had the handler attached
   this.count++;
}
MyClass.prototype.attachOnclick = function(elem)
{
    var self = this;
    elem.onclick = function() {self.onclickHandler(this); }
    elem = null; //prevents memleak
}

var o = new MyClass();
o.attachOnclick(document.getElementById('divThing'))
AnthonyWJones