Skip to content

getInstance

ts
getInstance<T extends Base = Base>(el: Element | null, name: string): T | undefined

The instance of name on el, mounted or not.

Usage

ts
// `el` may be null — a querySelector() result passes straight through.
const 
dialog
=
getInstance
<
Dialog
>(
document
.
querySelector
('[data-component="Dialog"]'), 'Dialog');
if (
dialog
?.
$isMounted
)
dialog
.
close
();

Parameters

  • el (Element | null) — the element to read.
  • name (string) — the component name.

Return value

  • T | undefined.

Why it is a function of its own

One map read and no scan. The caller already holds the element and the name, so there is nothing left to search — which is what makes it different from a filter over getInstances().

It is also the answer to "is this element's instance there yet", which every plural form loses by returning a list.

Why el accepts null but the return is not

el accepts null so a querySelector() result can be passed straight through. The two ways of having no instance — no element, and an element without one — are the same answer to the caller, and undefined says it for both. Narrowing the parameter to Element would buy nothing back: the body reads an optional map either way, so the only thing a stricter type produces is a ! at every call site asserting something the function never needed.

The return stays T | undefined, and that asymmetry is deliberate. An absent element is a fact the caller may reasonably not know; an absent instance is a fact the caller must handle.

There is no getMountedInstance

The result is one object, so a caller who needs the live one reads .$isMounted on it. A second export would only hide that check behind an undefined that means two things.

Detached elements

This form reads the element's instance map directly and never consults the DOM, so it answers for a detached element as readily as for a connected one.

MIT Licensed