BlockView

Class of @saij/wp-app-framework/view; your view extends it.

import { BlockView } from '@saij/wp-app-framework/view';

The base class of the view script of a block (Block.view.js next to the block class). The runtime creates one instance per block on the page.

Members

mount()

mount(): void

Sets the view up: find elements, listen to events. Override it.

unmount()

unmount(): void

Releases what listen() and onUnmount() do not cover. Override it if needed.

element

get element(): Element

The root element of the view: the root element of the block, or the document element for a document view.

document

get document(): Document

The document of the view: in the preview of the block editor the one of the canvas iframe.

window

get window(): Window

The window of the view: in the preview of the block editor the one of the canvas iframe.

isPreview

get isPreview(): boolean

Whether the view runs in the preview of the block editor.

find()

find(selector: string): Element | null

The first element below the root element that matches a selector, without elements of nested blocks with view scripts.

ParameterTypeDescription
selectorstringA CSS selector.

Returns Element | null: The element, or null.

findAll()

findAll(selector: string): Element[]

The elements below the root element that match a selector, without elements of nested blocks with view scripts.

ParameterTypeDescription
selectorstringA CSS selector.

Returns Element[]: The elements in document order.

data()

data(key: string): DataValue

A value of the view data of your theme or plugin, set in PHP with ViewData::set().

ParameterTypeDescription
keystringThe key of the value.

Returns DataValue: The value; an unknown key throws an error that names the known keys.

loadScript()

loadScript(url: string, attributes?: Record<string, string | boolean>): Promise<void>

Loads an external script into the document of the view, once per URL and document.

ParameterTypeDescription
urlstringAn https: URL or a protocol-relative one (//…).
attributes?Record<string, string | boolean>Further attributes of the script element; true for an attribute without value.

Returns Promise<void>: Fulfilled once the script has loaded; rejected if it fails to load.

listen()

listen(target: EventTarget, type: string, handler: (event: Event) => void, options?: AddEventListenerOptions | boolean): void

Adds an event listener that is removed when the view unmounts.

ParameterTypeDescription
targetEventTargetThe element, document or window to listen on.
typestringThe event type, e.g. click.
handler(event: Event) => voidThe listener.
options?AddEventListenerOptions | booleanThe options of addEventListener().

onUnmount()

onUnmount(cleanup: () => void): void

Runs a function when the view unmounts, after unmount(): for observers, timers and the like.

ParameterTypeDescription
cleanup() => voidThe function to run.