Monday, January 4, 2021

Bind elements

Ever needed to set the text of an element asynchronously?

Sometimes we want to use data that is dynamic or is stored outside our file or project.

In those cases, when we get the data, we can bind it with our elements.

Here's a simple example:

HTML:

<p data-test="p1">Placeholder 1</p>
<p data-test="p2">Placeholder 2</p>
<p data-test="p3">Placeholder 3</p>

JS:

var mockedAsyncData = {
     p1: "Hello",
     p2: "World",
     p3: "!!!!!"
}
var targetElements = document.querySelectorAll("[data-test]");

targetElements.forEach( element => {
    var attrValue = element.getAttribute("data-test");

     element.innerHTML =
mockedAsyncData[attrValue];
});
 

In this example, we set up 3 p elements with placeholders, and when the JS runs, it populate the p elements with the values from the data object.

Using vanilla JS works well, but if you'd like to put less code you can use a famous library: the KnockOutJs. 

It does exactly what's above (and much more) with less lines of code.

HTML:

<p data-bind="text: p1">Placeholder 1</p>
<p data-bind="text: p2">Placeholder 2</p>
<p data-bind="text: p3">Placeholder 3</p>

JS:

var viewModel= { 
    p1: "Hello",
    p2: "World",
    p3: "!!!!!"
};

ko.applyBindings(viewModel);

And that's it. The only thing to remember is to use data-bind="text: ..., and to use ko.appyBlindings() with the data. 


KnockoutJs is also able to iterate through arrays (like displaying a list from a template), read values and much more.

No comments:

Post a Comment