07 - Add items
The previous chapter rendered the Todo list with *for.
Now bring back the draft input and use it to add new items to
todos.
The input uses *lazy. Lazy input keeps the typed value
available to draft, but avoids a full host refresh for each
edit. That keeps ordinary typing from rebuilding the Todo list on every
keystroke.
Code
<script src="/sercrod.js"></script>
<serc-rod data='{"draft":"","todos":[{"title":"Buy milk","done":false},{"title":"Pay bills","done":true}]}'>
<h2>Todo</h2>
<p *if="todos.length === 0">No todos yet.</p>
<ul *else>
<li *for="todo of todos">
<span *if="todo.done">[x]</span>
<span *else>[ ]</span>
<span>%todo.title%</span>
</li>
</ul>
<p>
<label>
Title:
<input type="text" *input="draft" *lazy>
</label>
</p>
<p *if="draft">Draft: %draft%</p>
<p *else>Type a Todo title.</p>
<button type="button" @click="if(draft.trim()){ todos.push({ title: draft, done: false }); draft = '' }">
Add
</button>
</serc-rod>
How to read add
*input="draft" *lazykeeps the input connected todraftwithout forcing a full refresh for every edit.*if="draft"shows the draft only after there is text to add.- The Add button checks
draft.trim(), pushes a new Todo, then clearsdraft. - The loop updates because
todosnow contains another item.
Result
Todo
No todos yet.
- [x] [ ] %todo.title%
Draft: %draft%
Type a Todo title.
Next
The next step will toggle each Todo from inside the loop.