Weather forecasts with DOM API, fetch and JS classes

In this exercise we display weather forecasts. We use JavaScript to make the presentation interactive: download the data from the internet and display it dynamically.

DOM API

The DOM API allows JavaScript to completely control (edit, add, remove) the HTML objects constituting the web page. Please look at the example in documentation, we will be using similar operations.

We start, as usual, with the page in exercise/index.html. Please edit the files exercise/exercise_weather.js and exercise/style_weather.css to complete the exercise.

JS Classes

Classes allow us to organize our program around objects (“object-oriented programming”) and makes code easier to reuse - do the same actions with many objects. An object contains data (called properties) and functions (called methods).

First, we convert the code from the previous part into a class.

Inheritance (extends) allows us to create a sub-type with different behaviour (for example class Dog extends Animal). In our case, we will extend the Forecast class to change its data source: the child class ForecastOnline will download its data from the internet to provide a real forecast.

fetching JSON data from the internet

The data displayed in a visualization is most often not part of the code. Instead it is stored in data files and downloaded separately from our server or an external service.

This data can be downloaded using the Fetch API. Fetching is an asynchronous operation (we have to wait some time for the response), therefore it uses JS Promises. Please read the linked documentation to see the examples.

We can get a forecast in the JSON format using Yahoo Weather, for example the query for Lausanne is:

http://query.yahooapis.com/v1/public/yql?format=json&q=select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Lausanne") and u="c"

Optional: Interactive choice of the city

If you feel confident with DOM, fetch and classes, let’s combine them all into a more advanced system.