Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `:` in `on:click` work, in Svelte?

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.

like image 923
Chase May Avatar asked Nov 15 '19 21:11

Chase May


Video Answer


3 Answers

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.

like image 75
Rich Harris Avatar answered Oct 23 '22 23:10

Rich Harris


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.

like image 23
Félix Adriyel Gagnon-Grenier Avatar answered Oct 24 '22 00:10

Félix Adriyel Gagnon-Grenier


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.

like image 1
Frank Dinies Avatar answered Oct 24 '22 00:10

Frank Dinies