webstd-ui / view

Define the visual elements of your web app using a hierarchy of views
0 stars 0 forks source link

View modifiers #3

Closed markmals closed 1 year ago

markmals commented 1 year ago

Modifiers allow you to apply behavior to any arbitrary HTML element rather than needing to create a component or custom element, e.g.

export class LinkModifier implements ViewModifier<HTMLAnchorElement> {
    onAppear({ target }: ViewModifier.Context<HTMLAnchorElement>) {
        target.addEventListener("click", event => {
            event.preventDefault()
            console.log(target.href)
        })
    }
}

const enhanceLink = modifier(LinkModifier)

const ui = () => html`<a href="https://example.com" ${enhanceLink()}>Go to there</a>`

Creating a new custom element is not always desirable as it adds a new element to the DOM which could mess up styling, forces you to contend with the shadow DOM, and often make it difficult to implement accessibility or progressive enhancement. Using a view modifier you can attach stateful behavior to any DOM element without adding extra elements at runtime.

markmals commented 1 year ago

Closed in 2a699ee