Skip to content
Advertisement

WeakMap with event.target

Edit: turns out nothing is actually wrong with the second snippet (my real code). On one page it works, and on another it doesn’t. Yea for underlying errors.

I’m creating a DOM element and giving that DOM element to a WeakMap as a key. Then, with JQuery event delegation/event listener, I’m trying to retrieve the saved key but it’s returning undefined:

JavaScript

Anyone know what’s wrong or an alternative method to save data for a DOM element that doesn’t have an ID?

Edit: I’m kinda annoyed that the example I made works but my own code doesn’t… (some bits look redundant. This is modeled after my actual code, so not all the missing pieces are here, just pragmatically) but here’s the apparently working code:

JavaScript
JavaScript

Advertisement

Answer

Two possible issues:

  1. target is the innermost element that was clicked. You probably want this or event.currentTarget instead, which is the element on which you hooked the event handler (which may be an ancestor element to target).

  2. Your jQuery code hooks up the click event on all div elements, not just that one, but you only have that one div in the WeakMap. If you click a different div, you’ll naturally get undefined because that other div isn’t a key in the map.

Here’s an example (I’ve added a span within the div we have in the map to demonstrate #1, and also added a second div to demonstrate #2):

JavaScript
JavaScript

You’ve mentioned that in your real code you’re using event delegation. currentTarget and this are both fine in that case as well:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement