javascriptdomeventsthissvelte

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)
}

Solution

  • 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.