smelte icon indicating copy to clipboard operation
smelte copied to clipboard

Switch on:change doesn't fire

Open michaelfig opened this issue 4 years ago • 4 comments

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!

michaelfig avatar Aug 04 '20 02:08 michaelfig

<input type="checkbox" on:click={toggle} checked={isEnabled} /> Enabled

works as I expect.

michaelfig avatar Aug 04 '20 02:08 michaelfig

    <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.

michaelfig avatar Aug 04 '20 02:08 michaelfig

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>

micha-lmxt avatar Sep 07 '20 09:09 micha-lmxt

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" />

awhitford avatar Dec 28 '20 12:12 awhitford