ken
ken

Reputation: 9013

addEventListener not attaching to the right scope

I am using the native DOM's addEventListener event like so:

const domElement = document.getElementById('ember464');
domElement.addEventListener('click', dosomething);
this._listeners.push({target: domElement, type: 'click', callback: dosomething});

this registered the event and stores it in a _listeners array so it can be cleaned up later. The good news is that this event does attach to the DOM but event though the target is clearly scoped to just the single button, the handler seems to fire whenever a click is detected anywhere on the document!

Am I doing something wrong?

p.s. here's the browser inspector looking at the _listener array ... note that highlighting the "target" does indeed point only to the button that I'm trying to target. AKA, the target is the DOM node, not the selector used to identify the node.

image


I've now looked at the debugger at the targeted DOM element and I see the following:

enter image description here


For anyone brave enough, here's a working demonstration of the code. The second button is triggered by the "click" event is the subject of this issue:

https://ui-animate.firebaseapp.com/

The full source code is here: link

Upvotes: 1

Views: 76

Answers (1)

ken
ken

Reputation: 9013

Ok, the problem was in a bit of code I hadn't illustrated in the question. Modern browsers all support the DOM method addEventListener but in order to support older browsers who only have attachEvent I had added the following abstraction:

registerListener(target, type, callback) {
  const addListener = target.addEventListener || target.attachEvent;
  const eventName = target.addEventListener ? type : 'on' + type;

  addListener(eventName, callback);
},

The problem with this is that the "this" context is lost in the call. So instead I changed to the following:

registerListener(target, type, callback) {
  const listenerFunction = target.addEventListener ? 'addEventListener' : 'attachEvent';
  const eventName = target.addEventListener ? type : 'on' + type;

  target[listenerFunction](eventName, callback);
},

Upvotes: 1

Related Questions