Svelte – events and differences from JS

In a reactive framework Svelte don’t have to use addEventListener… Firstly, it will not work, because many elements on the page are created after it is loaded, and then they also change in the process. And secondly, this is not necessary.

Alternative to addEventListener

However, addEventListener can be used because Svelte is just plain JS. And you can even find some elements if you put it inside a function. onMount

<script>
import {onMount} from “svelte”;
onMount(async () => {
document.addEventListener();
});
script>

Abandoning addEventListener will only add pros. You no longer need to search for items by getElementById, querySelector or querySelectorAlland then process each forEach… You will also not need to check whether the item is selected or not. Etc. All this saves time – no need to write extra code.

All this replaces adding events directly to the element in the right place in the html.

For example, we add all sorts of events to the div element:

<div
class=“cell description edit”
contenteditable=“true”
bind:innerHTML=“{budget.description}”
on:input=“{saveUsersData (budget)}”
on:paste=“{handlePaste}”
on:keydown=“{handleKeydown}”
> div>

This is the cell where you can edit the text, which will be immediately saved after the change.

On event: input = {saveUsersData (budget)}

Function saveUsersData data is transferred to the backend every time our block is edited:

function saveUsersData(deposit) {
getFetch(‘deposit / save-user-data /’
+ deposit.user_id_time + ‘/’
+ deposit.time + ‘/’
+ deposit.date + ‘/’
+ deposit.deposit
);
}

On event: paste = {handlePaste}

On this event, we will catch the insertion of text into this block, remove the tags and paste the usual text from the clipboard:

function handlePaste(e) {
e.preventDefault();

// Get data from the clipboard in plain text
var text = (e.originalEvent || e)clipboardDatagetData(‘text / plain’);

// We insert ourselves
document.execCommand(“insertHTML”, false, text);
}

On event: keydown = {handleKeydown}

This event will allow us to catch keystrokes on the keyboard and perform some actions:

function handleKeydown(e) {
if (e.key === ‘Enter’) {
e.preventDefault();
document.execCommand(‘insertHTML’, false,

);
}
}

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *