dgraham / eslint-plugin-jquery

Disallow jQuery functions with native equivalents.
MIT License
209 stars 22 forks source link

rules/no-data: Prefer WeakMap to $.data #7

Closed dbarnespaychex closed 7 years ago

dbarnespaychex commented 7 years ago

Just wondering: why encourage WeakMap instead of HTMLElement.dataset?

dgraham commented 7 years ago

The dataset API lets you store string keys and values in an element's data- attributes. A WeakMap allows arbitrary objects to be associated with an element by using the element itself as the key.

const data = new WeakMap()
data.set(element, new Date())

When the element is removed from the tree and garbage collected, the weak reference inside the map is cleared too.