gpt4 book ai didi

javascript - 在自身和 setTimeout 中发出解除绑定(bind) "DOMSubtreeModified"

转载 作者:行者123 更新时间:2023-11-29 21:41:40 25 4
gpt4 key购买 nike

我有以下问题:

setTimeout(function() {
myElement.bind("DOMSubtreeModified", function() {

if (something == true) {
console.log("Keep outputting this message");
} else {
console.log("Unbind event");
myElement.unbind("DOMSubtreeModified");
}
});
}, 3600);

由于某些原因,解除绑定(bind)不起作用,它会在更改 myElement 后不断重新启动关联的功能。

我确实在控制台中反复看到“解除绑定(bind)事件”消息 something != true

最佳答案

我认为不再推荐bindunbind。尝试使用 on/off 代替:

setTimeout(function() {
myElement.on("DOMSubtreeModified", function() {

if (something == true) {
console.log("Keep outputting this message");
} else {
console.log("Unbind event");
myElement.off("DOMSubtreeModified");
}
});
}, 3600);

我也不确定 jQuery 是否正确处理了这个用例。您正在删除事件处理程序,而 jQuery 仍在“等待”处理程序执行并获取其结果。您可以异步解除绑定(bind),让事件处理程序执行先完成:

setTimeout(function() {
myElement.on("DOMSubtreeModified", function() {

if (something == true) {
console.log("Keep outputting this message");
} else {
console.log("Unbind event");
setTimeout(function() {
myElement.off("DOMSubtreeModified");
}, 10);
}
});
}, 3600);

您可以防止此事件被多次绑定(bind)(推荐):

function handleDOMChange() {
if (something == true) {
console.log("Keep outputting this message");
} else {
console.log("Unbind event");
this.unbind("DOMSubtreeModified");
}
}
// ....
setTimeout(function() {
if(-1 == $.inArray(handleDOMChange, button.data('events').DOMSubtreeModified) {
myElement.bind("DOMSubtreeModified", handleDOMChange);
} else {
console.warn("DOMSubtreeModified already bound!");
}
}, 3600);

关于javascript - 在自身和 setTimeout 中发出解除绑定(bind) "DOMSubtreeModified",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com