Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Svelte using the 'this' keyword in this scenario?

I'm going through the tutorial for Svelte and came upon this example, and am confused as to how this is working. (I cut out some other code not relevant to question, full example here: https://svelte.dev/tutorial/tick)

<script>
   async function handleKeydown(event) {
     const { selectionStart, selectionEnd, value } = this;

     await tick();
     this.selectionStart = selectionStart;
     this.selectionEnd = selectionEnd;
   }
</script>

<textarea value={text} on:keydown={handleKeydown}></textarea>

Could someone please explain the logic of how 'this' is being used here? I don't understand how it knows to reference the value within the textarea. Does it have something to do with the function being called by the textarea and creating a context within the function referencing the textarea element?

And also why something like the code below does not work? (console log's undefined)

function logger(event) {
 console.log(event.value)
}
like image 639
serp002 Avatar asked Sep 17 '25 03:09

serp002


1 Answers

this is provided by the DOM.

Form MDN's article on this in inline event handlers:

When the code is called from an inline event handler attribute, its this is bound to the DOM element on which the listener is placed.

svelte is a framework that builds on top of the DOM, but essentially on:keydown={handleKeydown} translates to a DOM event handler binding that has the above quoted property.

like image 171
trincot Avatar answered Sep 19 '25 16:09

trincot