This is a super simple question, yet it bothers me that I am not completely understanding what is happening here, because I really like svelte and want to understand it.
There is this awesome video about passing data from a child to a parent: https://www.youtube.com/watch?v=lqvY_0gJf_I&list=PLoWoeRXn334kDuFrZqIqHrFCN71fSZE4X&index=1&t=1804s
Their first way of doing it id the two-way data binding.
It essentially works as in this REPL https://svelte.dev/repl/24adfb0a93734265952e2870155aeb49?version=3.43.1
I simply do not fully understand the flow of the data here (and in svelte in general). If I change something in the rendered Input-field this means essentially that I am changing something in the child, right? In this case I assume the
- thing that happens is that the
person
variable in the child is changed by the user - As it has the
bind
directive, it somehow passes this data from the child to the parent - In the parent, the instance of the child component is initialized with passing the value of
p
(a variable initialized in the parent with a value) to the exported variableperson
from the child - somehow the variable
p
is changed in the parent by modyfing the value in the child and a reactive value in the child (the variableupper
) is updated.
Now my question is: Why is this variable p
updated and is there any intuitive understanding of this bind:<variable>
directive. I simply can't wrap my head around it.
I think there are also other possibilities to pass data from a child to a parent (like with event dispatching). But lets start with this one;)
//App.svelte
<script>
import Box from './inp.svelte'
let p = 'MyName'
$: nameUpper = p.toUpperCase()
</script>
<Box bind:person={p} />
<p>Reactive value in the parent component: {nameUpper}</p>
<hr />
// inp.svelte
<script>
export let person = 'valueInChild'
</script>
<input type="text" placeholder="put the name here" bind:value={person} />
binding_callbacks
and later you'll see the callbacks that were created for your various bindings. Try following this output code for a start. – Emelia