Working with Javascript and Rune reactivity
With runes, reactivity extends beyond the boundaries of your .svelte files.
<script>
import { createCounter } from './counter.svelte.js';
const counter = createCounter();
</script>
<button on:click={counter.increment}>
clicks: {counter.count}
</button>export function createCounter() {
let count = $state(0);
return {
get count() { return count },
increment: () => count += 1
};
}counter.svelte.js
In counter.svelte.js we created a reactive piece of state called count using $state(0) and it returns two usable functions:
get count() { return count }This is a getter function for the
countproperty.When you access the
countproperty on the returned object, this getter function is invoked, and it returns the current value of thecountstate.This allows you to retrieve the current value of
countas if it were a regular property, but behind the scenes, it is dynamically pulling the latest reactive state.
increment: () => count += 1This is an arrow function that increments the value of
countby 1.Since
countis reactive, any part of your Svelte component that depends oncountwill automatically update when this method is called.
App.svelte
First the javascript code is imported, and assigned to a variable. Then we can access those returned functions using the dot . to access them.
Last updated