-1

I'm trying to override the function attached to the event listener but when the event is triggered the old one is still called.

var element;
var newHandler = () => {
  if((element = this.getElementsByClassName('someClass')[0]) != null){
    this.removeEventListener('DOMNodeInserted', handler )
    element.insertAdjacentHTML('beforeend', "<a>Hello</a>");
  }
}

var handler = () => {
  handler = newHandler;
  var scriptTag = document.createElement('script');
  scriptTag.src = "someScript.js";
  document.head.appendChild(scriptTag);
}

document.addEventListener('DOMNodeInserted', handler);

Any kind of help is really appreciated. Thanks a ton!

Davide Modesto
  • 225
  • 3
  • 9
  • what makes you think that `handler = newHandler` would change the event listener that was passed to `addEventListener`? – zzzzBov Aug 15 '17 at 19:10
  • Thanks for the comment. I think "handler = newHandler" should do the job. – Davide Modesto Aug 15 '17 at 21:18
  • Maybe I wasn't clear, I understand that you *think* that that will work. I was asking *why* do you think that will work. In any case, it absolutely won't work (as you've already seen) and you'll need to learn more about the JS event API. – zzzzBov Aug 15 '17 at 21:21
  • I tought that overriding the pointer of the identifier ( handler ), from which the function is called, to the newHandler was enought to do what i want, so the next time the event will be fired, the handler will be called and the newHandler will be executed. At this point what should i do? – Davide Modesto Aug 15 '17 at 21:33
  • I was reading my first comment and I realized its nosense so sry... – Davide Modesto Aug 15 '17 at 21:44
  • "overriding the pointer of the identifier" JS doesn't use pointers in this manner. "At this point what should I do?" [more research](https://meta.stackoverflow.com/q/261592/497418). Spend some time learning the APIs and searching for how event binding and unbinding work in JavaScript. – zzzzBov Aug 15 '17 at 22:40

1 Answers1

0

Found the solution

var element;
var newHandler = () => {
  if((element = this.getElementsByClassName('someClass')[0]) != null){
    document.removeEventListener('DOMNodeInserted', intermediary )
    element.insertAdjacentHTML('beforeend', "<a>Hello</a>");
  }
}

var handler = () => {
  handler = newHandler;
  var scriptTag = document.createElement('script');
  scriptTag.src = "someScript.js";
  document.head.appendChild(scriptTag);
}

var intermediary = () => handler();

document.addEventListener('DOMNodeInserted', intermediary );

I think the problem was caused by a kind of first level cache.

Davide Modesto
  • 225
  • 3
  • 9