我有以下问题:
setTimeout(function() {
myElement.bind("DOMSubtreeModified", function() {
if (something == true) {
console.log("Keep outputting this message");
} else {
console.log("Unbind event");
myElement.unbind("DOMSubtreeModified");
}
});
}, 3600);
由于某些原因,unbind无效,它会在myElement更改后不断重新启动相关功能。
我在something != true
答案 0 :(得分:1)
我相信不再推荐bind
和unbind
。请尝试改为使用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仍在等待"你正在删除事件处理程序让处理程序执行并抓住它的结果。您可以异步取消绑定它以使事件处理程序执行首先完成:
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);
您可以阻止此事件多次绑定(推荐):
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);