-
Notifications
You must be signed in to change notification settings - Fork 0
valueStore
import { valueStore } from 'svelte-object'
const store = valueStore(initialValue)
It's a writable store that
1. can be bidirectionally bound to nearest Object
/ Array
parent
2. can be formatted when value changed
3. can have validation
Bidirectional means when this store updates, the parent store will also be updated, and vice versa.
By using store.setName(name: string)
the store can be bound to the nearest parent.
store.setParent(parentId: string)
will instead of using the nearest parent, use a parent with the given id
attribute.
Its name "pre-change" indicates this is run before a change.
The returned value from this function will therefore be the formatted value.
So we can force the behaviour of our valueStore
, by running a function.
For instance, if our store has a min
value — we can format it using store.prechange
:
export let min: number | undefined = undefined
store.prechange = (v) => {
if(v === undefined)
return
if(min !== undefined && v < min)
v = min
return v
}
// If `min` changes, we update the store — which will run the prechange logic
$: store.update(), min
store.onValidate
— store validation
Svelte REPL
To validate a store, you can use
store.validate()
validate(trigger: 'forced' | 'change' | 'blur' = 'forced')
trigger
will indicate what triggered the validation. 'forced'
will be interpreted as both 'change'
and 'blur'
Note
You can update ALLvalueStore
s in anObject
orArray
by ex.<Object let:store> ... store.validate()
To create validation, set store.onValidate
to your validation method:
store.onValidate = (ValidationEvent) => { ... return error(...) }
type ValidationEvent = {
trigger: { blur: boolean, change: boolean }
value: T
error(
errorMessage: string,
show?: (value: T) => boolean,
update?: (value: T) => string
)
warning(
warningMessage: string,
show?: (value: T) => boolean,
update?: (value: T) => string
)
}
These are called when the store value updates:
show?: (value: T) => boolean
the error will show as long as this returns true
ex: (value) => value < min
update?: (value: T) => string
the error message will be updated to the returned string
ex: (value) => (value.length - min) + ' over character limit'
To trigger store.validate('blur')
you may attach it to an element:
<input on:blur={() => store.validate('blur')} />
The store.error
and store.warning
are Writable<{ message: string, show?: ..., update?: ... }>
The values of the stores are emitted from <Value let:error let:warning>
So you can show them like
<Value let:error let:warning>
{#if error}
<span>{error.message}</span>
...
⚠ Documenation for svelte-object 1.4.2
👉 Basic Usage
⭐ Component Usage ⚠
Components
Object.svelte ⚠
Array.svelte ⚠
Value.svelte ⚠
Concepts
valueStore ⚠
bind ⚠