【问题标题】:issue unbinding "DOMSubtreeModified" within itself and setTimeout在自身和 setTimeout 中发出解除绑定“DOMSubtreeModified”的问题
【发布时间】:2015-09-16 13:44:25
【问题描述】:

我有以下问题:

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

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

由于某种原因,取消绑定不起作用,它会在 myElement 更改后不断重新启动关联函数。

我确实在控制台中反复看到一次“取消绑定事件”消息something != true

【问题讨论】:

标签: javascript jquery events bind unbind


【解决方案1】:

我认为 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 仍在“等待”处理程序执行并获取它的结果。您可以异步解绑它,让事件处理程序执行首先完成:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多