Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class methods as event handlers in JavaScript?

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?

like image 472
JacobE Avatar asked Oct 23 '08 09:10

JacobE


People also ask

What are the different methods to associate an event handler?

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.

How do you bind an event handler to a class method in typescript?

In ES5, we can very easy bind a event to DOM using the native way: document. addEventListener() , or a jQuery way, $(element). bind() , $(element).

How many types of event handlers are there?

However, there are two other ways of registering event handlers that you might see: event handler properties and inline event handlers.


1 Answers

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

like image 181
pawel Avatar answered Sep 22 '22 23:09

pawel