Hacker News new | ask | show | jobs
by akira2501 1145 days ago
Why not just use the 'dataset' property of the element itself? Then you can use querySelectorAll to find your selected rows automatically:

    node.querySelectorAll('tr[data-selected="true"]');
In other words.. "use the DOM to handle the DOM."
1 comments

That'd work for this specific case, but I think that was just a simplified example. A Map can store a value of any type, while the dataset property will always be a string. If you're only working with strings, it's a great option since you don't need to maintain a side data structure at all. But, serializing and deserializing arbitrary objects would be expensive.
Couldn't you do elementReference.foo = whateverTypeYouWant? No need to restrict things to just the data attribute.

This wouldn't work if you need to know the order of the properties.

This generally doesn’t play nice with TS code bases and is generally considered an anti-pattern since there’s chances for collisions etc , you might get away using a unique symbol index but it’s still not good design.
I'm not sure about DOM elements, but tacking random new properties onto Javascript objects can cause them to become deoptimized by the runtime.
Any reference for this?
I found [1] to be a pretty good summary of the key concepts that support the claim. The article, unfortunately, doesn't come right out and say it. But, it talks about how object shapes (a common JS object model) can be used as guards for inline caches (IC) to generate efficient machine code for property access. If you add a new property, you change the shape, which causes the cache guard to fail. That leads to deoptimization since the assumptions made about the call site when the code was compiled no longer hold. That call site is now either polymorphic or megamorphic, depending on the type of IC used and its level of polymorphism.

[1] -- https://mathiasbynens.be/notes/shapes-ics

Chances for collisions are pretty much nil if you use some prefix standard will never use, like $.

    el.$my_data = ...
And in practice it works just fine.