0

Assume I have a javascript function createMyElement which returns a node that can be inserted into an HTML document.

In order to function properly, the code of the node created by createMyElement has to listen for events on the global document at least as soon as it is inserted in the document.

My first attempt was to add DOMNodeInsertedIntoDocument and DOMNodeRemovedFromDocument listeners to the node at creation time that add and remove the needed listener on document in turn.

However, the mutation events are deprecated by now (and don't seem to work reliably across browsers), so I am looking for a better solution.

Adding the listener for events at document at the creation time of the node would work. However, this doesn't seem to be a good solution as it would create memory and performance leaks: Even after the node was being removed from the document again and not needed anymore, the listener (and its references to the node) on the document would still persist.

000
  • 26,951
  • 10
  • 71
  • 101
Marc
  • 4,327
  • 4
  • 30
  • 46
  • I'm not sure I understand - why does the node created by `createMyElement` need to listen to events on document? Event listening usually works the other way around. – robertc Jun 20 '11 at 22:57
  • My application generates custom events using the built-in event system. My idea was to dispatch these events on the document as they are really global events. E.g. if a global state changes, an event is dispatched. All nodes that use this state have to listen to this changed event. – Marc Jun 21 '11 at 14:09

2 Answers2

0

Use a series of function callbacks or on-demand script callbacks to serialize the events.

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
0

Since I originally asked my question, the substitute for mutation events, namely mutation observers as defined in http://www.w3.org/TR/domcore/#mutation-observers, have been implemented in a number of browsers.

So a simple answer to my own question is to simply use mutation observers on the document to listen for nodes to be inserted or removed.

An even better way, however, is to use the new custom elements from https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/custom/index.html, which gives one insertedCallbacks and removedCallbacks for custom elements.

Marc
  • 4,327
  • 4
  • 30
  • 46