factordog factordog -3 years ago 89
Javascript Question

Remove Event Listener In an Object Literal Lost this reference

Currently working on a small project using an OLOO style approach.
Problem found here

So the issue I am facing is that I have an event handler.

eventHandler: function() {
console.log('Hit');
testSelector.removeEventListener('click', this.eventHandler, false);
}


Now what happens is that I want this to be removed after the first click. However this does not seem to work as I expected. I am binding the object this reference yet there seems to be something that I am missing in what is actually going on here. Would anyone be able to clarify what is actually happening or where I went wrong?

Answer Source

I'm not an expert in OLOO, but I can see two issues in your example:

  • the this inside an eventListener callback handler refers to the node so you need to take care you're referencing the same this in both methods ( add/removeEventListener )

  • removeEventListener won't work if the listener parameter isn't the same as addEventListener, and when you use bind you're actually creating a new function (so you have to keep track of that to)

in code:

var testSelector = document.querySelector('.test');

var object = {
  init: function() {
    this.ref = this.eventHandler.bind(this)
    testSelector.addEventListener('click', this.ref, false);
  },
  eventHandler: function() {
    console.log('Hit');
    testSelector.removeEventListener('click', this.ref, false);
  }
}

object.init();

https://jsbin.com/hejenuraba/1/edit?js,console,output

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download