Custom primitives
Wrap any value that changes over time in the Seitu contract, and every binding works with it.
Built-in primitives use two public helpers: createSubscription and createReadableSubscription. You can use them too. A handle you build this way works with useSubscription in React, Vue, Solid and Svelte, with createComputed, and with debounce and throttle.
| Helper | Gives you |
|---|---|
createSubscription({ onFirstSubscribe }) | subscribe, notify and size. onFirstSubscribe runs when the first subscriber arrives. The function it returns runs after the last subscriber leaves. |
createReadableSubscription(get, subscribe, notify, getServer?) | A Readable & Subscribable handle. Subscribers receive get() each time you call notify(). |
Read-only: listen to the browser
Attach listeners in onFirstSubscribe, so a handle that nothing subscribes to costs nothing. Pass getServer to set the value used during SSR and hydration.
import { , } from 'seitu'
export function () {
const { , } = ({
: () => {
.('visibilitychange', )
return () => .('visibilitychange', )
},
})
const = () =>
typeof === 'undefined' || . === 'visible'
return (, , , () => true)
}Writable: add set()
Spread the readable handle and add set. Accept a value or an updater, like the built-ins do, and call notify() after the value changes.
import { , } from 'seitu'
import type { , , } from 'seitu'
export interface SearchParam
extends <string | null>, <string | null>, <string | null> {}
export function (: string): SearchParam {
const { , } = ({
: () => {
.('popstate', )
return () => .('popstate', )
},
})
const = () =>
typeof === 'undefined'
? null
: new (.).()
return {
...(, , , () => null),
: () => {
const = typeof === 'function' ? (()) :
const = new (.)
if ( === null) ..()
else ..(, )
.(., '', )
()
},
}
}Rules
- Call
notify()after the value changes, never before. Subscribers readget()when they are notified. - Keep
get()cheap and pure. Bindings call it on every render. Cache the value if reading it is expensive. - Guard browser globals.
get()can run on the server. Checktypeof windowortypeof documentand passgetServerso the first client render matches the server HTML. - Attach listeners lazily. Put
addEventListener, observers and timers inonFirstSubscribe, and return the cleanup.
Edit on GitHub
Last updated on