Dom: Allow custom "get the parent" algorithms for EventTargets

Created on 5 Mar 2018  路  11Comments  路  Source: whatwg/dom

In the future we could allow custom get the parent algorithms. Let us know if this would be useful for your programs. For now, all author-created EventTargets do not participate in a tree structure.

I'd like to see that future. That is, the ability to create a tree structure for author-created EventTargets like the one we have with Nodes, with bubbling and capturing, and so forth. Two points in support of this:

  1. It would just make the platform more consistent when all EventTargets behave similar or have ways to do so. Right now we have a "weird" limitation to keep in mind when we work with custom EventTargets.
  2. Listening just to a parent instead of each of its children simplifies our code when we work with Nodes, and same can apply to author-created EventTargets.

An example use case:
Let's take the classic Todo app example. Imagine that each todo item is a custom EventTarget emitting "change" events, and the whole list is an array. Now, if we need to respond to any change in the list, say, recalculate the number of items, we have to add event listeners to each item. However, if we could define our array as the parent for each item where events could bubble to (or be captured on) the parent, we could get away with just one listener on the array. Since the items and the array already have strong coupling, adding an extra "parent" pointer wouldn't make difference in terms of the design.

additioproposal needs implementer interest events

Most helpful comment

We are building web extensions which would like to implement events, to propagate critical occurrences from the browser api event listeners back to the extension business logic layer.

We would want to leverage the EventTarget implementation to build propagation, rather doing it in an ad-hoc way.

The ability to bubble the events is going to be a huge advantage given we can override/implement a custom 'get the parent' algorithm.
The shadow tree capabilities are not really necessary for author created event targets.

All 11 comments

To what extent are you interested in also having shadow tree capabilities for your custom event targets? E.g., being able to hide event targets from composedPath() and such. (This came up in #684.)

@annevk I cannot think of a use case for shadow tree capabilities. If we are building tree structures out of these custom EventTargets solely to propagate events, having a capability of hiding/skipping certain nodes seems superfluous--one can just avoid putting those hidden nodes into the said tree structure.

We are building web extensions which would like to implement events, to propagate critical occurrences from the browser api event listeners back to the extension business logic layer.

We would want to leverage the EventTarget implementation to build propagation, rather doing it in an ad-hoc way.

The ability to bubble the events is going to be a huge advantage given we can override/implement a custom 'get the parent' algorithm.
The shadow tree capabilities are not really necessary for author created event targets.

I'm currently using a polyfill for EventTarget in NodeJS environments. I see Deno will support EventTarget out of the box, so at least we're going to get nice usage from EventTarget.

But, for my polyfill, I'm creating a custom "get the parent" implementation via WeakMap as to not pollute the the property list.

````
/**

  • @typedef {Object} EventDispatcherEventTargetPrivateFields
  • @prop {Map
  • @prop {function():EventDispatcherEventTarget} getParent
    */

/** @type {WeakMap} */
export const privateEventTargetFields = new WeakMap();

export default class EventDispatcherEventTarget {
constructor() {
privateEventTargetFields.set(this, {
listeners: new Map(),
getParent: () => null,
});
}

/* ... */
````

getParent() gets checked and called during dispatchEvent(), much like how browsers do it. The problem is my custom implementations has to know to set privateEventTargetFields.get(eventTarget).getParent = callback;

The reason is I'm using a context => listener => client configuration for socket connections. Client connections themselves emit events which can be captured by the listener (TCP or WebSocket). Propagation can be stopped or it can continue bubble to the context (service that spawns the listeners).

It makes sense because the application architecture is tree-like already. Unfortunately, if we decide to port to Deno we will not be able to the official EventTarget implementation because spec has no "get the parent" function and no standard as to how to pass the "get the parent" function in the constructor.

Edit: I just want to add that this continues to make more sense considering we can do new EventTarget() now which I use for custom events that has nothing to do with the DOM. Also, some objects (eg: service workers, window, navigator) extend EventTarget but have little to no relation to the DOM (and workers can't even access the DOM), so I would say Events has branched outside the basic DOM scope already.

+1 for this... In my case, it's just a whim. I'm currently writing a tiny widget's library where widgets are tree nodes (they have a parent and children), so I wanted to extend EventTarget and add event bubbling support, I stumbled upon this because I tried overriding dispatchEvent, so that:

class ElementNode extends EventTarget {
  constructor () {
    super();
    this.parent   = null;
    this.children = [ ];
  }

  append (nodes) {...}
  remove (node) { ... }
  walk (visitor) { ... }
  dispatchEvent (event) {
    super.dispatchEvent(event);
    if (event.bubbles && this.parent) {
      this.parent.dispatchEvent(event); // Losing event.target here :(
    }
  }
}

The original event.target target is lost across calls because I'm manually dispatching the event in the parent, which then sets the target to be the parent. After reading the spec (https://dom.spec.whatwg.org/#concept-event-dispatch) I realized that the get the parent function can't be overridden and besides I can't just reassign event.target as it's read-only (and I understand why)

If I were to think of the benefits I'd say that we would gain standardization... Allowing this customization can open the doors for other libraries or frameworks to rely on the EventTarget and CustomEvent APIs instead of everyone rolling their own "event emitter" solutions.

Deno actually uses a somewhat custom method of "get the parent" that allows custom overloading. The check occurs by checking if the EventTarget "is a node" by checking if has a nodeType property. Then it uses .parentNode. That means an Javascript Object that has nodeType can potentially return a parent (via .parentNode).

https://github.com/denoland/deno/blob/704e1e53307130012da974f42d2cad94e07b5664/op_crates/web/02_event.js#L438

This is piggybacking off Node, but to write a proper shim for it (I've tried it), you have to implement Node, ChildNode, ParentNode, Document. and some others that my escape me at the moment. That would be a lot of work for user agents to include and force them to require support something far more complicated just EventTarget. The Deno team is using something custom as is for lack of a standard, and I can totally understand doing it like that instead of writing all of Document.

I can only realistically conclude that the EventTarget may be constructed with a eventTargetInit object that may have a get the parent value. So you can maybe do something like new EventTarget({ getParent: myMasterParentFn }), for example. It keeps it strictly within EventTarget without telling user agents to support more complex types, or having developers need to add on something heavy like JSDom.

Hm... we don't want to run arbitrary scripts just to get the parent. It needs to be some kind of setter/getter that UA would implement on EventTarget interface.

@rniwa Do you think that having that setter/getter is a simple thing to do? And if so, what determines if that should be added to the spec?

To be honest, I'm just curious

@rniwa Do you think that having that setter/getter is a simple thing to do? And if so, what determines if that should be added to the spec?

Basically, you need to get at least two implementors interested in your proposal, write a DOM/HTML spec PR and WPT tests.

My concerns with a getter/setter is a hard reference could leave an object in memory, prohibiting it from being garbage collection. With DOM nodes, once a child is detached from its parent, .parentNode becomes null (or undefined, not sure). The parent can then be garbage collected if it's no longer referenced. That's one of the reasons why I leaned to a function.

The other idea I had with my custom implementation is a EventTarget parent registry. Basically, instead of the child explicitly stating what it's parent is, a global registry can be used. eg: parent = EventTargetParentRegistry.get(child). Here, a user agent can basically keep a dictionary of sorts since no child can have multiple parents.

A pure JavaScript solution (polyfill) could look something like this:

````js
class EventTargetParentRegistry {
/** @type {WeakMap>} */
static #registry = new WeakMap();

static get(child) {
return this.#registry.get(child)?.deref();
}

static set(parent, child) {
this.#registry.set(child, new WeakRef(parent));
}

static delete(child) {
this.#registry.delete(child);
}
}
````

During the get the parent phase, the user agent (or polyfill) would use EventTargetParentRegistry.get(child) for EventTargets that are not Node objects.

My concerns with a getter/setter is a hard reference could leave an object in memory, prohibiting it from being garbage collection. With DOM nodes, once a child is detached from its parent, .parentNode becomes null (or undefined, not sure). The parent can then be garbage collected if it's no longer referenced. That's one of the reasons why I leaned to a function.

I'm not sure how that is consistent with the idea that EventTarget can have a parent. Is the idea that the event will propagate to the parent object only if that's still alive?? Literally nothing in the web platform works like that. I'm not certain we want to add API like this given its behavior will be highly dependent on a particular implementation of GC.

Was this page helpful?
0 / 5 - 0 ratings