Ask questionsExport reference to inner slider object

I would like to call the .set() method of the inner slider instance, like this:

import NoUiSlider from '@woden/svelte-nouislider'

let slider

<NoUiSlider bind:slider />

<button on:click={() => { slider.set(10) }}>Set slider to 10</button>

I think that if you export the created instance returned by .create().


Answer questions cbenz

With Svelte components wrapping other libs, it's always the same question: should we keep private the library instance? If so, each method has to be wrapped which can be a pain to maintain.

For example, I wrapped Mapbox GL with Svelte, and the Map class has tons of methods, so I exposed the instance (cf this line).

Another idea I sometimes used is to leverage Svelte "bind" mechanism. For example here we could have a value property that would be reactive to changes, allowing things like:

import NoUiSlider from '@woden/svelte-nouislider'

let value

<NoUiSlider bind:value />

<button on:click={() => { value = 10 }}>Set slider to 10</button>

When clicking on the button, value would be updated, but when manipulating the slider itself, value would be also updated.

That's higher-level than exposing the inner instance, but I think both could be made, so the user could choose between reactivity style (binding a property) or imperative style (calling the instance methods directly).

Implementation of value would be something like:

// In Slider.Svelte

export let value

$: sliderInstance.set(value)

  (values, handle, unencoded, tap, positions) => {
    value = values // or unencoded?
    dispatch("update", { values, handle, unencoded, tap, positions })

(did not test it; but I plan to do it, and if it's satisfying I'll submit a real PR)


Related questions

No questions were found.
Github User Rank List