我用纯 JS 编写代码,我需要为类中的事件监听器提供可重用的回调。需满足以下条件:
- 可被其他函数重用
- 事件监听器需要由其他函数撤销
- 我需要传递参数(事件)
- 我需要能够从回调中调用另一个函数 (this.doSomething())
我尝试将回调定义为方法和函数表达式,但每次我解决一个问题时都会发生另一个问题。我也在这里解决了很多问题,但仍然无法使我的代码正常工作。
class Foo {
constructor() {
functionA()
this.howAndWhereToDefineThisCallback = function(event) {
event.preventDefault();
this.doSomething();
}
}
functionA() {
let el = document.getElementById('element1');
el.addEventListener( 'click', howAndWhereDefineThisCallback );
this.functionB();
}
functionB() {
let el = document.getElementById('element1');
el.removeEventListener( 'click', howAndWhereToDefineThisCallback );
}
doSomething() {
// something meaningful
}
}
如何修改我的代码以按照我刚才描述的方式使用它?
最佳答案
这里有一个实现:
// Callback defined outside the class.
function callback(event) {
this.doSomething();
}
class Foo {
constructor(cb) {
// Important: You have to bind it.
this.cb = cb.bind(this);
this.functionA();
}
functionA() {
let el = document.getElementById('element1');
el.addEventListener('click', this.cb);
}
functionB() {
let el = document.getElementById('element1');
el.removeEventListener('click', this.cb);
}
doSomething() {
console.log('doing something...');
}
}
const foo = new Foo(callback);
// foo.functionB();
<button id="element1">
Click here
</button>
关于javascript - 类内可重用的事件监听器回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762048/