const $ = require('jquery'); const moment = require('moment'); const _ = require('underscore'); const Backbone = require('backbone'); function reduceOpenWeather(item) { // Openweather returns timestamps in seconds. Moment requires them in milliseconds. const ts = moment(item.dt * 1000); const weatherBlock = item.weather[0]; // console.log(item, item.temp); return { 'timestamp': item.dt, 'icon': `wi-owm-${weatherBlock.id}`, 'summary': weatherBlock.description, 'tempHigh': parseInt(item.temp.max, 10), 'tempLow': parseInt(item.temp.min, 10), 'tempMorn' : parseInt(item.temp.morn, 10), 'tempDay' : parseInt(item.temp.day, 10), 'tempEve' : parseInt(item.temp.eve, 10), 'tempNight' : parseInt(item.temp.night, 10), 'datelong': ts.format(), 'time': item.dt, 'date': ts.format('D/M'), 'day': ts.format('ddd') }; } function reduceDarkSky(item) { const ts = moment(item.time * 1000); return { 'timestamp': item.time, 'icon': weatherIcons.get(item.icon), 'summary': item.summary, 'tempHigh': parseInt(item.temperatureHigh, 10), 'tempLow': parseInt(item.temperatureLow, 10), 'datelong': ts.format(), 'time': item.time, 'date': ts.format('D/M'), 'day': ts.format('ddd') }; } const WCollection = Backbone.Collection.extend({ 'url': '/weather', 'parse': function(data) { return data.list.map((item) => { // Reduce the data return reduceOpenWeather(item); }); } }); const WView = Backbone.View.extend({ 'tagName': 'div', 'template': _.template(` <% _.each(data, function(item) {%>
<%= item.day %>
<%= item.date %>
<%= item.tempHigh %>° / <%= item.tempLow %>°
<%= item.summary %>
<%= item.tempMorn %>°
<%= item.tempDay %>°
<%= item.tempEve %>°
<%= item.tempNight %>°
<% }); %>`), 'initialize': function() { _.bindAll(this, 'render'); this.collection = new WCollection(); this.listenTo(this.collection, 'reset sync', _.debounce(_.bind(this.render), 128)); this.collection.fetch(); }, 'render': function() { if (this.collection.length !== 0) { const data = { 'data':this.collection.toJSON() }; this.$el.html(this.template(data)); } } }); module.exports = WView;