javascript - toggle event listener not working on javascript matchmedia (within a Class)
问题描述
Im trying to toggle a click event listener using matchmedia. My goal is to add the eventlistener when the screen size is less than or equal 768px and removeEventListener above 768px. The event listener is removed and added when I write them as seperate functions like below:
function clickHandler() {
alert("media worked");
}
function myFunction(x) {
if (x.matches) { // If media query matches
document.getElementById("resources").addEventListener("click", clickHandler)
} else {
document.getElementById("resources").removeEventListener("click", clickHandler)
}
}
var x = window.matchMedia("(max-width: 768px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
HOWEVER, when I write it as a class function below (which is what I need, so that i can remove the myFunction listener later on), the click eventListener gets added, but does not get removed. The console.log of 'smaller screen' and 'wider screen' changes with the width successfully, so i'm thinking it must be something to do with the way I've set up the class function, constructor and/or the methods.
Sorry for the noob question - I've been at it for ages! This is my first time posting so any help/guidance is greatly appreciated.
export default class testController {
constructor(){
this.x = window.matchMedia("(max-width: 768px)")
}
myFunction(e) {
function clickHandler(){
console.log("clicked")
}
if (e.matches) { // If media query matches
document.getElementById("vid-button").addEventListener("click", clickHandler, false);
console.log("smaller screen")
} else {
document.getElementById("vid-button").removeEventListener("click", clickHandler, false);
console.log("wider screen")
}
}
testAdd(){
this.myFunction(this.x) // Call listener function at run time
this.x.addListener(this.myFunction) // Attach listener function on state changes
}
testRemove(){
this.x.removeListener(this.myFunction);
}
}
tController = new testController();
tController.testAdd();
解决方案
推荐阅读
- c# - C# - 在 IEnumerable 中找到第一个枚举并转换为字符串
- javascript - 如何重用现有赛普拉斯测试中的功能,并在新测试中调用它?
- aurelia - 无法读取属性“api”
- c# - EF Core - 存储在父级的子集合的单一选择
- ruby - 如何在 Docker 中调试已安装的 Ruby gem?
- command-line-interface - 多字命令行参数的样式指南规则?
- arrays - 在 bash shell 中使用输出文件中的数组
- python - 与 Tensorflow 中的常规 LSTMCell 相比,使用 CudnnLSTM 进行训练时的结果不同
- python-3.x - 将 Python 模块导入 Sublime Text 3
- .net - Select.Pdf:安全透明方法访问安全关键方法