首页 > 解决方案 > How do you call a object method from within an addEventListener() call?

问题描述

I am adding an event listener to a button inside of an object method. I am attempting to add a call to another method function but when I use this.reset() the 'this' points to the listener//button rather than the object itself.

This code has been refactored into an object and was working fine before. In that case I didn't need to use 'this'.

const colorGame = {
    reset: function() {...},

    init: function() {
        for (let i = 0; i < modeSwitches.length; i++) {
            modeSwitches[i].addEventListener("click", function() {
                modeSwitches[0].classList.remove('selected');
                modeSwitches[1].classList.remove('selected');

                // These two lines are why I can't use anonymous functions
                this.classList.add('selected'); 
                this.textContent === 'Easy' ? numSquares = 3 : numSquares = 6;
                this.reset();
            });
        }

        ...
    resetButton.addEventListener('click', function() {
            this.reset(); // This call also fails with the same error
});

Error in Chrome browser console : colorGame.js:78 Uncaught TypeError: this.reset is not a function

My intent is to use colorGame.reset() and have that called when the buttons are clicked.

标签: javascriptobjectmethodsthisaddeventlistener

解决方案


让您的colorGame对象通过给它一个方法来实现EventListener 接口。handleEvent然后您可以将对象本身绑定为事件处理程序,并handleEvent在事件发生时调用其方法。

thisin的值handleEvent将是colorGame对象。

const colorGame = {
  handleEvent: function(event) {
    // handle events here
    switch (event.type) {
      case "click":
        this.reset();
        break;
        
      default:
        console.log("unhandled event type");
    }
  },

  reset: function() {
    console.log("reset was called");
  },

  // Bind the colorGame object instead of binding functions
  init: function() {
    for (let i = 0; i < modeSwitches.length; i++) {
      modeSwitches[i].addEventListener("click", colorGame);
    }

    resetButton.addEventListener('click', colorGame);
  }
}


推荐阅读