I am experimenting with Svelte and following the official tutorial. At https://svelte.dev/tutorial/reactive-assignments, I am instructed to use this line of code:
<button on:click={handleClick}>
What is the purpose of the colon? Why isn't it simply <button onclick=...
?
I found the Svelte API documentation on element directives, which provides usage examples within Svelte, but I still don't understand how this is valid JS syntax, or how it is transformed to such. I don't understand how the colon works (as separate from understanding its usage).
I can understand that this was a way to implement a single directive for all DOM event attributes, but its actual functioning is not that transparent to me.
Others have explained the point about it being compiled into JavaScript, so I'll address this part:
Why isn't it simply
<button onclick=...
?
The onclick
attribute is an existing HTML attribute (that you shouldn't use). The semantics are very different — the string value is evaluated as JavaScript when the click happens. It's a bad practice because any functions you call must live in the global scope.
on:click
is a Sveltism that links the button's click event to a locally defined function. The :
is a generic piece of syntax that says 'this is a directive rather than an attribute' — where 'directive' can mean an event handler (on:...
), a binding (bind:...
), a transition (in:...
/out:...
/transition:...
) and so on.
The first thing to understand is that the code in Svelte components is actually not the resulting JavaScript that is sent to the browser, so about:
I still don't understand how this is valid JS syntax
It is not. It is "compiled" into valid JavaScript by SvelteJS's compiler.
I have not roamed through the source code, but I presume the colon in this case, is used to denote the event handler binding directive (on
) from the event itself (click
).
For an actual demonstration of the compilation: you can visit the REPL and select the "Js output" tab to see the compiled JavaScript code.
The svelte <button on:click ... />
becomes after the compilation step a normal event listener for the event "click" on that button.
getEventListeners(elem) will reveal that. Thats why multiple handlers are possible,
for example <button on:click on:doWhatever...
>
So, equivalent to add elem.addEventListener() in plain js.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With