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 gets called, but the _clickCount member is inaccessible, or this points to some other object.
Any good tips/articles/resources about this kind of problems?
There are two recommended approaches for registering handlers. Event handler code can be made to run when an event is triggered by assigning it to the target element's corresponding onevent property, or by registering the handler as a listener for the element using the addEventListener() method.
In ES5, we can very easy bind a event to DOM using the native way: document. addEventListener() , or a jQuery way, $(element). bind() , $(element).
However, there are two other ways of registering event handlers that you might see: event handler properties and inline event handlers.
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'); } }
EDIT almost 10 years later, with ES6, arrow functions and class properties
class ClickCounter { count = 0; constructor( buttonId ){ document.getElementById(buttonId) .addEventListener( "click", this.buttonClicked ); } buttonClicked = e => { this.count += 1; console.log(`clicked ${this.count} times`); } }
https://codepen.io/anon/pen/zaYvqq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With