Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple parameters on Svelte action

Accordingly to the Svelte documentation:

Actions are functions that are called when an element is created. They can return an object with a destroy method that is called after the element is unmounted

I want to pass multiple parameters to a Svelte action function, but only the last one is recogonized

DEMO

<script>
    function example(node, arg1, arg2) {
        // the node has been mounted in the DOM
        console.log(arg1, arg2) // Should display 'a b', but actually only displays 'b undefined'
        return {
            destroy() {
                // the node has been removed from the DOM
            }
        }
    }
</script>

<h1 use:example={'a', 'b'}>Hello World!</div>

Is there any viable solution that avoid the use of a single object as parameter?

<script>
    function example(node, arg) {
        // the node has been mounted in the DOM
        console.log(arg) // Returns a object with the arguments
        return {
            destroy() {
                // the node has been removed from the DOM
            }
        }
    }
</script>

<h1 use:example>Hello World!</div>

<!-- Passing parameters -->
<h1 use:example={{
    arg1: [50, 75, 100],
    arg2: true
}}>Works like a charm!</h1>
like image 620
henriquehbr Avatar asked Sep 20 '25 12:09

henriquehbr


1 Answers

The content between {} can be any JavaScript expression, and when you write 'a', 'b' you are using the comma operator, so the value of the entire expression will be 'b'.

You could use an array instead.

Example (REPL)

<script>
  function example(node, [arg1, arg2]) {
    console.log(arg1, arg2)
    return {
      destroy() {
        // the node has been removed from the DOM
      }
    }
  }
</script>

<h1 use:example="{['a', 'b']}">Hello World!</h1>
like image 105
Tholle Avatar answered Sep 23 '25 04:09

Tholle