Svelte – Immutable

1 min read


flash.js

export default function flash(element) {
	requestAnimationFrame(() => {
		element.style.transition = 'none';
		element.style.color = 'rgba(255,62,0,1)';
		element.style.backgroundColor = 'rgba(255,62,0,0.2)';

		setTimeout(() => {
			element.style.transition = 'color 1s, background 1s';
			element.style.color = '';
			element.style.backgroundColor = '';
		});
	});
}

ImmutableTodo.svelte

<svelte:options immutable/>

<script>
	import { afterUpdate } from 'svelte';
	import flash from '../sources/flash';

	export let todo;

	let div;

	afterUpdate(() => {
		flash(div);
	});
</script>

<!-- the text will flash red whenever
		the `todo` object changes -->
<div bind:this={div} on:click>
	{todo.done ? '๐Ÿ‘': ''} {todo.text}
</div>

<style>
	div {
		cursor: pointer;
		line-height: 1.5;
	}
</style>

MutableTodo.svelte

<script>
	import { afterUpdate } from 'svelte';
	import flash from '../sources/flash';

	export let todo;

	let div;

	afterUpdate(() => {
		flash(div);
	});
</script>

<!-- the text will flash red whenever
		the `todo` object changes -->
<div bind:this={div} on:click>
	{todo.done ? '๐Ÿ‘': ''} {todo.text}
</div>

<style>
	div {
		cursor: pointer;
		line-height: 1.5;
	}
</style>

Immutable.svelte

<script>
	import ImmutableTodo from './components/ImmutableTodo.svelte';
	import MutableTodo from './components/MutableTodo.svelte';

	let todos = [
		{ id: 1, done: true, text: 'wash the car' },
		{ id: 2, done: false, text: 'take the dog for a walk' },
		{ id: 3, done: false, text: 'mow the lawn' }
	];

	function toggle(id) {
		todos = todos.map(todo => {
			if (todo.id === id) {
				// return a new object
				return {
					id,
					done: !todo.done,
					text: todo.text
				};
			}

			// return the same object
			return todo;
		});
	}
</script>

<h2>Immutable</h2>
{#each todos as todo}
	<ImmutableTodo {todo} on:click="{() => toggle(todo.id)}"/>
{/each}

<h2>Mutable</h2>
{#each todos as todo}
	<MutableTodo {todo} on:click="{() => toggle(todo.id)}"/>
{/each}

dan import ke App.svelte

	<CRUD />
	<CircleDrawer />
	<!-- <HackerNews /> -->
	<Immutable />

hasilnya akan seperti ini …

Okay sudah berhasil ya…. berikut link github ada disini … cya….

Bima Sena

Leave a Reply

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