sercrod

Binding & events (advanced)

In earlier chapters, you used simple bindings with %name%, *print, *input, and @click. This chapter combines them with conditionals and lists:

1. Toggle a panel with a flag and aria

Start with a boolean field in data and a button that toggles it. Use *if so the panel is only rendered when the flag is true. At the same time, bind aria-expanded so assistive tools can see the state.

Code

<serc-rod data='{"open":false}'>
	<button
		type="button"
		@click="open = !open"
		:aria-expanded="open ? 'true' : 'false'">
		Toggle panel
	</button>

	<section *if="open">
		<h2>Panel</h2>
		<p>This section is only in the DOM when the panel is open.</p>
	</section>
</serc-rod>

Sample

Panel

This section is only in the DOM when the panel is open.

The button uses @click="open = !open" to flip the flag. *if controls whether the panel exists in the DOM. The :aria-expanded binding updates the attribute whenever open changes.

2. Actions on each row in a list

Next, use *for to render a list of items and give each row its own action button. Sercrod supports an index and a value:

Here is a small checklist that toggles done for each item:

Code

<serc-rod data='{
	"items":[
		{"label":"Read the guide","done":false},
		{"label":"Try the examples","done":false},
		{"label":"Embed Sercrod into a page","done":false}
	]
}'>
	<h2>Checklist</h2>

	<ul>
		<li *for="i, item of items">
			<button type="button" @click="item.done = !item.done">
				<span *if="item.done">Undo</span>
				<span *else>Done</span>
			</button>

			<span *if="item.done">[x]</span>
			<span *else>[ ]</span>

			%item.label%
		</li>
	</ul>

	<p *if="items.filter(function(x){ return x.done; }).length === 0">
		Nothing checked yet.
	</p>

	<p *else>
		Some items are done.
	</p>
</serc-rod>

Sample

Checklist

  • [x] [ ] %item.label%

Nothing checked yet.

Some items are done.

Each row uses @click to flip item.done. The summary at the bottom uses *if and a small array expression to decide which text to show.

For a slightly larger example that uses the same pieces to build a tiny app, see A minimal todo list.

Next: Nested Sercrod

You now have several patterns for working with bindings and events, from simple toggles to list actions and attribute bindings.

In the next chapter, you will compose multiple Sercrod hosts in the same page and see how they interact.

Next: Nested Sercrod