Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue unbinding "DOMSubtreeModified" within itself and setTimeout

I have following issue:

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

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

For some reason the unbind is not working, it keeps reinitiating associated function after myElement is changed.

I do see "Unbind event" message in console repeatedly once something != true

like image 704
Ilja Avatar asked Feb 27 '26 01:02

Ilja


1 Answers

I believe that bind and unbind are no longer recommended. Try using on/off instead:

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

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

Also I'm not sure if jQuery handles correctly this use case. You're removing the event handler while jQuery still "waiting" for the handler to execute and grab it's result. You may unbind it asynchronously to let the event handler execution to finish first:

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

You might prevent this event from being bound more than once (recommended):

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);
like image 130
kbtz Avatar answered Feb 28 '26 13:02

kbtz