[英]Reusable event listener callback within class
I write code in pure JS and I need to have reusable callback for my event listener within the class. 我用纯JS编写代码,并且需要在类中为事件侦听器使用可重用的回调。 It is required to meet following:
必须满足以下条件:
I tried define callback as method and also as function expression but every time I solve one issue another occurred. 我尝试将回调定义为方法和函数表达式,但每次解决一个问题时,都会发生另一个问题。 I have walked through many questions here too but still can not make my code to work.
我在这里也经历了许多问题,但仍然无法使我的代码正常工作。
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
}
}
How can I modify my code to use it the way I just described? 如何修改我的代码以按照我刚才描述的方式使用它?
Here you have an implementation: 在这里,您有一个实现:
// 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>
If you want to reuse your callback function, simply put it outside of your class scope. 如果要重用回调函数,只需将其放在类范围之外即可。 In order to call another function from your callback, just put that function as a argument of your callback, for example:
为了从回调中调用另一个函数,只需将该函数作为回调的参数即可,例如:
var howAndWhereToDefineThisCallback = function(event, anotherCallback) {
event.preventDefault();
if (anotherCallback) anotherCallback();
}
To use the callback in your class method: 在类方法中使用回调:
el.removeEventListener( 'click', function(event) {
howAndWhereToDefineThisCallback(event, this.doSomething);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.