In part one and part two of this series, we looked at how rivets handles data binding and then how to use rivets to show and hide elements on the page. In this post, things are going to get a little more interesting. We are going to cover how to consume JSON.
This is the need that originally lead me to rivets. You can use something like “document.getElementsById(‘[some id]’)” and the “el.value(‘[some value]’)” method to set a value within an element upon successful completion of a “XMLHttpRequest()” request but data binding allows you to lay out your page much easier. Let’s take a look at a simple example.
Within the above example, we are getting the current weather for Milwaukee, WI from YQL. Once the request successfully completes, it saves the important data into the ‘items’ variable. We then display the data using {curly brackets}. Within this example, we are looking at flat data. There is data about the sunrise, sunset, etc. Next, let’s see how you would handle a multi-day forecast.
The above example is much like the first example. You will notice that a “rv-each-forecast” attribute is being used to look over the items array, though. Rivets allows you to do nested loops, too. It is not needed in this case, but it is available.
Once again, if you have any questions? Feel free to drop a comment below or shoot me a message. These example are also on GitHub, so feel free to check them out there.