Skip to content

subscribeContext

ts
subscribeContext<T>(el: Element, key: ContextKey<T>, onProvide: ContextCallback<T>): () => void

The subscription behaviour of the WICG context protocol: every answer, as providers come and go.

Usage

ts
class 
Disclosure
extends
Base
{
static
config
= {
name
: 'Disclosure' };
group
?: GroupApi;
mounted
() {
return
subscribeContext
(this.
$el
,
DisclosureGroupContext
, (
group
) => {
this.
group
=
group
;
const
leave
=
group
.
join
(this);
// The teardown for *this* value. return () => {
leave
();
this.
group
=
undefined
;
}; }); } }

Parameters

  • onProviderequired. It runs synchronously for each answer and receives the value and the same unsubscribe function the helper returns.

Return value

  • the unsubscribe function. Call it from mounted()'s return value to get an unmount-scoped lifetime.

A new answer replaces; it never accumulates

The callback can return a teardown for the value it received. That teardown runs:

  • before the next different value;
  • on unsubscribe.

An identical value is not an answer, so nothing runs and nothing is torn down.

That is what lets a member move between groups correctly: join() returns its own leave, the teardown calls it, and a member that moves to a nearer group leaves the old one first.

When it fires

The trigger is the mount announcement, not a broadcast from the provider, and it runs after mounted().

The optional context-subscription module keeps one listener on the document, attached on the first subscription and never at import time.

Two contains() calls bound the cost per mount: the new provider must contain the consumer, and it must sit inside the provider that answers it now. A mount that changes nothing checks nothing.

What it holds

The registry holds nothing. A subscription is anchored on its consumer element through a WeakMap, and the iterable index holds WeakRefs that the sweep prunes.

Callback and teardown failures are isolated — callback.context-subscription-failed and callback.context-teardown-failed — so one consumer cannot stop the shared sweep.

context.ts and the Base graph import none of this optional state, so a page that never subscribes pays for none of it.

MIT Licensed