0

What options are available to store a DOM ref on a DOM element, such that the ref still exists in a Mutation Observer remove callback?

In this case, the data is a DOM reference to another DOM element that needs manually removed when the observed element is removed by an external script. Because of this, I can't simply store the data in a data-* attribute, because it is a DOM reference and not a string.

It seems that Jquery .data() properties are removed when the parent object is removed from the DOM. This makes sense, but creates a problem when the mutation observer needs to perform some type of destruct behaviour, and needs the data that was stored on the just-removed element, which is gone at the time the callback.

The elements don't have IDs, and setting them from the plug-in would defeat the unobtrusive design of the plug-in, which is why we are using mutation observers to begin with.

What options are available to store a DOM ref on a DOM element, such that the ref still exists in the Mutation Observer remove callback?

Nick
  • 10,904
  • 10
  • 49
  • 78
  • you can store data as own properties of the element instead of data- attribs – dandavis Dec 03 '14 at 04:44
  • That works, but strictly speaking, "expando" properties aren't part of the spec and some sources say they can cause memory leaks in certain browsers. See: http://stackoverflow.com/questions/1915341/whats-wrong-with-adding-properties-to-dom-element-objects. – Nick Dec 03 '14 at 05:09
  • the IE that link warns about is dead and gone (2009), along with most of the invisible problems. that leaves name conflicts. nothing is perfect, but i can assure that i personally have never encountered a problem storing well-named props. i do wish there was an allowed "tag" or "memo" property, but there's not, so you can abuse the html spec to store something under a rare attrib/prop, do something complicated with parallel arrays, limit yourself to Map()-supporting browsers, or tack on props. i'd go with props.If JQ has done it for years, it's workable. – dandavis Dec 03 '14 at 05:31

0 Answers0