在JavaScript中,使用bind()删除作为事件侦听器添加的函数的最佳方法是什么?
例
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.myButton.addEventListener("click", this.clickListener.bind(this));
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", ___________);
};
})();
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法就是跟踪每个添加了bind的侦听器.
以上示例使用此方法:
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.clickListenerBind = this.clickListener.bind(this);
this.myButton.addEventListener("click", this.clickListenerBind);
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", this.clickListenerBind);
};
})();
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
我正在尝试删除侦听器定义中的事件侦听器:
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
// remove this event listener here!
}
// More code here ...
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做?这=事件......谢谢.
我需要一种方法来获取视频的总时间长度和jquery的当前时间,并将其显示在几个<div>标签中.
<div id="current">0:00</div>
<div id="duration">0:00</div>
Run Code Online (Sandbox Code Playgroud)
我一整天都在搜索,我知道如何获取它们我只是无法显示它们.#jquerynoob
我有一个这样的课程:
class Hanoi{
constructor(canvas) {
//construcor things
}
onMouseDown(e) {
for (var i = 0; i < this.pieces.length; i++) {
let piece = this.pieces[i];
if (piece.isClicked(e)) {
this.isDragging = true;
this.dragPiece = piece;
this.bound = evt => this.onMouseMove(evt);
this.canvas.addEventListener("mousemove", ev => {this.onMouseMove(ev)});
this.canvas.addEventListener("mouseup", ev =>{this.onMouseUp(ev)});
this.draw();
}
}
}
onMouseMove(e) {
this.dragPiece.x = e.clientX;
this.dragPiece.y = e.clientY;
this.draw();
}
onMouseUp(e) {
this.canvas.removeEventListener("mousemove", this.onMouseMove);
this.canvas.removeEventListener("mouseup", this.onMouseUp);
this.isDragging = false;
this.draw();
}
}
Run Code Online (Sandbox Code Playgroud)
onMouseDown 添加了两个事件侦听器,但是由于有箭头函数,所以在调用 onMouseUp 时我无法删除它们。
处理这个问题的最佳方法是什么?
我使用 ID 在输入框中附加事件侦听器。所以它工作正常,但我想删除事件侦听器,它对我不起作用。
document.getElementById("myInput").addEventListener("keyup", function({
console.log(document.getElementById("myInput").value);
});
document.getElementById("myInput").removeEventListener("keyup",function() {
});
Run Code Online (Sandbox Code Playgroud) javascript ×4
events ×2
listener ×2
bind ×1
duration ×1
ecmascript-6 ×1
html ×1
html5 ×1
html5-video ×1
jquery ×1
oop ×1
time ×1