javascript - 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.
解决方案
让您的colorGame
对象通过给它一个方法来实现EventListener 接口。handleEvent
然后您可以将对象本身绑定为事件处理程序,并handleEvent
在事件发生时调用其方法。
this
in的值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);
}
}
推荐阅读
- reactjs - 通过过滤每个 JSON 对象创建可定制的反应表
- nodemailer - 使用 G Suite OAuth2 使用 Nodemailer 发送群组电子邮件地址
- mysql - 从两列MySQL计算朋友
- amazon-web-services - 如何在 Amazon Sagemaker 上使用自定义 docker 容器创建超参数调整作业?
- prolog - 可能的错误或遗漏
- swift - 当我想用 JSONDecoder() 解码我的数据时,一些变量返回 nil
- typescript - 如何在数组中获取对象值的联合类型?
- html - 页面顶部不需要的导航
- javascript - Django SQL AJAX 调用没有响应
- rust - 如何检查货箱的所有可用夜间构建?