我正在尝试从与设置侦听器的位置不同的函数中删除具有绑定变量的事件侦听器。
我已经从同一函数中检测到this post that describes how to remove a bound listener,这与我要执行的操作不同:
function testBind(var1,var2){
//remove the bound event from within this function <<<
alert('bound event now removed');
}
function setEvent(){
var addEvent = document.getElementById("testBtn");
var boundYes = yesFunction.bind( this, this );
addEvent.addEventListener('mouseup', boundYes);
}
我发现的所有示例都在设置事件监听器的同一函数中删除了事件监听器:
addEvent.removeEventListener("mouseup", boundYes );
我知道使用bind每次都会创建一个新的事件侦听器,并且要删除该侦听器,您需要通过同一变量来设置和删除它。
如何从testBind
函数中正确删除事件监听器?
答案 0 :(得分:2)
如果(由于代码中的约束)this preferred solution is not possible,则另一个选择是通过自定义属性将处理程序与元素相关联:
addEvent.boundYes = boundYes; /* Assign boundYes function to element */
这将为您提供在'mouseup'
期间注销testBind()
事件时通过DOM元素本身访问此函数处理程序实例的方法:
function yesFunction() {
console.log('yesFunction');
}
function testBind(var1, var2) {
const addEvent = document.getElementById("testBtn");
const boundYes = addEvent.boundYes;
/* Check to see if boundYes associated with element */
if (boundYes) {
/* Remove the event listener from element */
addEvent.removeEventListener('mouseup', boundYes);
/* Disaccoaite the function from element */
addEvent.boundYes = undefined;
alert('bound event now removed');
}
}
function setEvent() {
var addEvent = document.getElementById("testBtn");
/* Prevent multiple boundYes handlers */
if (!addEvent.boundYes) {
var boundYes = yesFunction.bind(this, this);
addEvent.addEventListener('mouseup', boundYes);
/* Attach boundYes function to element */
addEvent.boundYes = boundYes;
}
}
setEvent();
testBind();
<button id="testBtn">testBtn</button>
答案 1 :(得分:1)
setEvent
的一个选项是返回绑定函数,以便testBind
可以删除它:
function testBind(boundListener, element) {
element.removeEventListener('mouseup', boundListener);
}
function setEvent() {
var element = document.getElementById("testBtn");
const yesFunction = () => console.log('listener running');
var boundListener = yesFunction.bind(this, this);
element.addEventListener('mouseup', boundListener);
return { boundListener, element };
}
const { boundListener, element } = setEvent();
testBind(boundListener, element);
<button id="testBtn">click</button>
您将需要 some 方法来传递绑定函数。如果您在setEvent
中创建它,则setEvent
应该返回绑定函数,或者调用testBind
本身或类似的东西。您还可以在setEvent
外部创建绑定函数,将其传递给setEvent
,然后将其传递给testBind
。