Svelte this & Component Binding
Transcript from the "this & Component Binding" Lesson
>> And then we also have the this binding, which is a way of getting a reference to an element inside your component. If you've used refs in React, this is a similar concept. So here we have a canvas, And when the component is rendered we want to paint to that canvas.
[00:00:21] Which means that we need to get a reference to the canvas so that we can get a reference to the canvas' context. Up here we have a value, let canvas. And once the component is mounted using the unmount callback, which we'll come to later, we're creating the canvas context using canvas.getContext('2d').
[00:00:40] If you haven't used Canvas programming four and this isn't familiar, don't worry. It's more straightforward than it looks. But we're not gonna get into it during this course, so just roll with it for now. All we need to do to make this work is populate this value by adding bind this to the canvas element And so now we have a nice animated, Canvas inside our component.
[00:01:19] Now, a note about the order in which everything happens here. So the script tag executes first before any content is actually rendered. Because very often, what happens inside the script tag determines what is gonna get rendered. So because of that, there's no way that this can have a value until later.
[00:01:38] So the unmount callback is the first time you're able to access the value of any element with a bind this directive. So far we've only looked at element bindings, but components can also have bindings. So here we have a component called Keypad, which is basically a custom form element, you can think of it that way.
[00:02:09] And what we want to do is get the value of what's been entered into the Keypad into the component that is using it. So that we can submit, for example, a pin number. And so inside the Keypad, we've created an EventDispatcher. And we have a submit event that happens when you click on the Submit button.
[00:02:40] But the value itself, we don't have any events for that. That is gonna be handled through the binding. And it's just like using a text input, we do bind:value. And on the right hand side, we give the name of the variable that it should be bound to.