smelte
smelte copied to clipboard
Switch on:change doesn't fire
Just wanted to know how to intercept Switch click events, or if they're broken. I have the following:
export let isEnabled;
function toggle() {
console.log('toggling', isEnabled);
// This function does asynchronous work, resulting in the parent toggling isEnabled when done.
}
// ...
<Switch value={isEnabled} label="Enabled" on:click={toggle} />
The expected behaviour is to see "toggling"
printed out, and have the Switch not change its setting when clicked, only when isEnabled
is updated.
Actually, the "toggling"
message is never printed, and the Switch changes its setting when clicked.
Thanks!
<input type="checkbox" on:click={toggle} checked={isEnabled} /> Enabled
works as I expect.
<div on:click|capture|stopPropagation={toggle}>
<Switch value={isEnabled} label="Enabled" />
</div>
does what I want, but it would be nicer for the Switch to support this usage directly.
Sounds a bit like the React way of doing things, where the Component is completely controlled by its props. How about this:
<script lang="ts">
import {Switch} from 'smelte/src';
let checked=false
let checktext = "click me";
const setCheck = (c:boolean) : string => {
if (checked){
if (Math.random()>.5){
return "Checked";
}
checked=false;
return "You failed to check me correctly";
}
return "click me";
}
$: checktext = setCheck(checked);
</script>
<Switch bind:value={checked}/>
<div>{checktext}</div>
https://github.com/matyunya/smelte/blob/6b054cfef5e354e294b5346e27e08131a21853f2/src/components/Switch/Switch.svelte#L52-L56
The check
handler is not presently exposed to the caller -- only the value
. The idea is to use bind:value
like:
<Switch bind:value={isEnabled} label="Enabled" />