1

I'd like to know if there's any reason to use jQuery's data over expando properties.

I'm converting a script that's currently using multiple event listeners to use only one listener on parent object, and wish to read arbitrary data objects from the element being clicked on (thus given through the event.target).

An old question regarding this problem exists here - Using jQuery's datastore vs. expando properties The answer that was given there is not explanatory at all and the memory leaks were fixed long time ago.

Thanks,
Bar Harel

Community
  • 1
  • 1
Bharel
  • 23,672
  • 5
  • 40
  • 80
  • "_jQuery's data_" Actually [data-*](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-*) attributes are native to HTML5, and [dataset of elements](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) has been around for a while. jQuery has just built more or less cross-browser implementation on these features. – Teemu Jan 28 '17 at 21:47
  • @Teemu Do they allow the addition of arbitrary javascript objects or only strings? – Bharel Jan 28 '17 at 21:49
  • As all attributes, they are strings. You can use JSON strings though, that having certain limits ofcourse. Generally, monkey-patching native HTML elements is not preferred, Prototype.js for example, is (or was) based on that, and now it's almost dead. – Teemu Jan 28 '17 at 21:50
  • 1
    @Teemu Well, I wish to use arbitrary objects. `element.myattrib = {"randomfunc": func}`. – Bharel Jan 28 '17 at 21:53
  • Why? You could store the name of the function to the attribute, and use that name to create a reference to the function. – Teemu Jan 28 '17 at 21:55
  • 1
    Because my objects are far more complicated, and I do not wish to create a global mapping (plus, I don't have a unique identifier for the objects) – Bharel Jan 28 '17 at 21:56
  • It is easy to create an identifier, and also without globals. At this point this begins to seem an XY problem. Maybe you should rather ask a question about how to delegate events for your specific purposes? – Teemu Jan 28 '17 at 22:06
  • Maybe not the newest, but still quite topical, [What's wrong with extending the DOM](http://perfectionkills.com/whats-wrong-with-extending-the-dom/). – Teemu Jan 28 '17 at 22:18

0 Answers0