Re: [whatwg/dom] Make it possible to observe connected-ness of a node (#533)

FrameMuse left a comment (whatwg/dom#533)

## Use case

I guess the main use case would be removing subscriptions. In my case, I have a (library based) "component" that saves reference to a constructed element, the component must support callbacks for engaging scripts when the element is connected and pause/suspend those scripts when it's disconnected.

In reality, it's a bit more complex since an element may not be disconnected while actually not being in the document. So it should take into account connection/disconnection **from a document** (either parents or the element itself is connected/disconnected).

For accurate work, when https://github.com/whatwg/dom/issues/1255 is implemented, the **document** connection events should fire or they should be accounted by a developer.

## Implementation Proposal

I see it as a separate `NodeLifeObserver` class, based on `MutationObserver`, `IntersectionObserver` signature. Though this also might be worth adding dispatched events (`addEventListener`).

```ts
type NodeLifeEntryCase =
  | "connected"
  | "disconnected"

  | "parentChanged"
  | "parentConnected"
  | "parentDisconnected"

  | "documentConnected"
  | "documentDisconnected"

interface NodeLifeEntry {
  target: Node
  case: NodeLifeEntryCase
}

class NodeLifeObserver {
  constructor(callback: (entry: NodeLifeEntry[]) => void) { }

  observe(node: Node): void
  unobserve(node: Node): void
  disconnect(): void
}
```

Additionally I need the moment when is reflowed since connection/disconnection may change the size, but you need to use this recalculated value. So I expect that e.g. `connected` event would occur **before** [relow](reflow - MDN Web Docs Glossary: Definitions of Web-related terms | MDN) and when it does occur, it would trigger additional `reflowed` event.

With this I come up with the following code that extends `NodeLifeObserver` for `Element`.

```ts
type ElementLifeEntryCase =
  | NodeLifeEntryCase
  | "reflow"


interface ElementLifeEntry {
  target: Element
  case: ElementLifeEntryCase
}

class ElementLifeObserver {
  constructor(callback: (entry: ElementLifeEntry[]) => void) { }

  observe(element: Element): void
  unobserve(element: Element): void
  disconnect(): void
}
```

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/533#issuecomment-2676255894
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/dom/issues/533/2676255894@github.com>

Received on Saturday, 22 February 2025 15:15:48 UTC