Class methods as event handlers in JavaScript?

前端 未结 4 1127
予麋鹿
予麋鹿 2020-11-29 00:59

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

Consider the following simple example:


            


        
4条回答
  •  情书的邮戳
    2020-11-29 01:41

    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

提交回复
热议问题