Recently I was given a task to consume an open rest based API from Open Weather using Ractive.js and HTML5’s Fetch API
The sample app here takes the city name as input and shows the corresponding weather information below it.
In order to get the JSON data from OpenWeather’s REST API, the first thing we need to do is get their free API key. The API can be called by simply passing in this app id as query parameter. That’s it!
Create an HTML5 element to be used as the front of the app. In our case, it’s div#container
.
Just for implementing the responsiveness, we’ve included the Bootstrap reference. The classes .row .col-md-6 .col-sm-12
takes care of responsiveness itself.
After adding ractive’s link, we’ve made sure that the code in the fiddle will be Ractive-aware.
The template is in the script tag. Note that we’ve set the script
’s type attribute to ‘text/ractive’ - though it can be just about anything except ‘text/javascript’. We can load a template in many ways. For convenience, we’ll include it in a script tag so that we don’t need to mess around with AJAX or multiline strings.
The curly braces e.g. are holding the data set inside the ractive function with e.g. ractive.set('location', JSON.stringify(data.name) + ', ' + JSON.stringify(data.sys.country));
The Ractive
constructor function will be used to set the Ractive context. The parameters with their description are:
el
: the element to which the front end will be renderedtemplate
: the Ractive templatedata
: the data for the front endRactive events looks a little different than pure HTML events, e.g. on-click. They’re catched in a samilar sense as that of jQuery.
Prepare the fetch request using the Request
constructor function and fire it using fetch(request)
.
The city input is stored in the localStorage instance as an array and displayed as the li
of ul
on click of each is the weather fetching request recap-ed.
See the whole code here.
Sources: