Info
In Svelte, apart from the dollar sign ('$'), another thing I hadn't quite figured out yet was 'Bind,' and I've been digging into it a bit during the holidays.
The core idea is this:
In Svelte, variables defined are all Observable. If they change, they will send updates to DOM components in a one-way manner.
However, when DOM components change, they don't alter the variables themselves. This is where Bind comes in handy, establishing a two-way communication channel between components and variables.
Example:
Here's a simple example that illustrates how 'bind' works and the difference between using it and not using it:
Without using 'bind':
<script>
let inputValue = '';
function handleChange(event) {
inputValue = event.target.value;
}
</script>
<input type="text" value={inputValue} on:input={handleChange}>
<p>Input Value: {inputValue}</p>
In the above code, we need to manually synchronize the value of the <input>
element with the inputValue
variable and update the inputValue
value in the on:input
event handler.
Using 'bind':
htmlCopy code<script>
let inputValue = '';
</script>
<input type="text" bind:value={inputValue}>
<p>Input Value: {inputValue}</p>
Here, we use 'bind:value' to directly bind the value of the <input>
element to the inputValue
variable. The benefit of doing this is that we don't need to manually listen to the on:input
event and update the variable; Svelte handles it automatically.
We can also use the 'bind' with the HTML native API, here's a simple case where we bind the href
attribute of an <a>
element:
<script>
let linkUrl = 'https://www.example.com';
</script>
<a href={linkUrl} bind:href={linkUrl}>Visit Example</a>
In this example, we bind the href
attribute of the <a>
element to the linkUrl
variable. When the value of linkUrl
changes, the href
attribute of the <a>
element also updates accordingly, achieving dynamic hyperlink updates.
Another example involving a checkbox:
<script>
let isChecked = false;
</script>
<label>
<input type="checkbox" bind:checked={isChecked}>
Check this box
</label>
<p>Checkbox is checked: {isChecked ? 'Yes' : 'No'}</p>
In this example, we bind the checked
attribute of the <input>
element to the isChecked
variable to keep the checkbox state in sync.
Official Example :
<script>
let w;
let h;
let size = 42;
let text = 'edit this text';
</script>
<label>
<input type="range" bind:value={size} min="10" max="100" />
font size ({size}px)
</label>
<div bind:clientWidth={w} bind:clientHeight={h}>
<span style="font-size: {size}px" contenteditable>{text}</span>
<span class="size">{w} x {h}px</span>
</div>
Concludsion
Svelte's 'bind' attribute makes data binding easy, reducing the need for manual DOM manipulation, improving code readability, and maintainability. You can use it to bind values and attributes of various HTML elements to keep them in sync.