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: /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)
}
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)
}
Share
Improve this question
asked Sep 28, 2020 at 12:25
serp002serp002
1361 silver badge12 bronze badges
4
-
About your final paragraph? How do you call
logger
? – trincot Commented Sep 28, 2020 at 13:00 - Could you provide feed-back? – trincot Commented Sep 29, 2020 at 13:44
- Sorry about that, thank you this makes a lot of sense! Appreciate you taking the time to answer! – serp002 Commented Sep 30, 2020 at 0:13
- Also regarding the logger function, I was calling it the same way as handleKeydown above, with on:keydown. But i was getting 'undefined' as the console. – serp002 Commented Sep 30, 2020 at 0:15
1 Answer
Reset to default 10this
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.