Dynamic Values & Update
The best things you can have in template literal are dynamic values. Lucky for Markup dynamic values are just functions that are automatically handled in the template.
Any function added to the template, as long as it is not an event handler, will be treated as a getter and be called to get the value to render or for an attribute.
The example bellow will render the count just fine. Using a function to return the value tells the template that the value might change in the future, so it needs to be re-called on update requests or state changes.
let count = 0;
const conter = html`
<p>${() => count}</p>
`;
You will learn a better way to have dynamic values when learning about states later. For now, let's focus on the function alone.
Update template
Just having dynamic values in the template does not do much. All it does is render the value returned.
The template still needs to know when to update. Enters the
update
method.
let count = 0;
const counter = html`
<p>${() => count}</p>
<button type="button" onclick="${countUp}">+</button>
`;
function countUp() {
count += 1;
counter.update()
}
counter.render(document.body)
The above example introduces 2 new functions in the template:
-
countUp
: used asclick
event listener on the button. -
counter.update
: used to tell the template about the value change.
update
is another method the template instance
exposes that you can use to tell the template to look into all
the dynamic values for a change. The template will get a new
value, do a shallow comparison and update the DOM if such
value has changed.
Important to know that this "re-check" happens
to all dynamic values in the template. This means that you can
update multiple values at once and call the
update
after to have the template update for all of
them.
It also means that the template will also re-check dynamic values that did not change. You will learn how to address this next when you learn about states.