/** * Created by mdonnel on 22/03/2017. */ let BitcoinModel = Backbone.Model.extend({ initialize: function () { this.set('url', '/btc'); let data = { lastGBP: 0.0, lastUSD: 0.0, lows: {gbp: 0, usd: 0}, highs: {gbp: 0, usd: 0}, eclass: '' }; this.set('btcdata', data); this.update(); }, update: function () { this.getBTC(); const now = new Date(); const mod = 60000 - (now.getTime() % 60000); let btcupdateFn = function() { this.update(); }; setTimeout(btcupdateFn.bind(this), mod + 10); }, recalc: function () { let data = this.get('btcdata'); let lastGBP = data.lastGBP; let lastUSD; let g = data.gbp; let u = data.usd; let lows = data.lows; let highs = data.highs; let eclass = data.eclass; if (data.lastGBP !== 0) { if (g > lastGBP) { eclass = 'up'; } else { eclass = 'down'; } } else { lows.gbp = g; lows.usd = u; highs.gbp = g; highs.usd = u; } lastGBP = g; lastUSD = u; if (g < lows.gbp) lows.gbp = g; if (u < lows.usd) lows.usd = u; if (highs.gbp < g) highs.gbp = g; if (highs.usd < u) highs.usd = u; data = { lastGBP, lastUSD, lows, highs, eclass }; this.set('btcdata', data); // total = myBTC * g; }, getBTC: function () { let self = this; let url = this.get('url'); $.ajax({ type: 'GET', url: url, data: '', dataType: 'json', timeout: 10000, //contentType: ('application/json'), headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'PUT, GET, POST, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type' }, success: function (data) { let gbp = data.bpi.GBP.rate_float, usd = data.bpi.USD.rate_float; let btcdata = self.get('btcdata'); btcdata.gbp = gbp; btcdata.usd = usd; self.set('btcdata', btcdata); self.recalc(); }, error: function (xhr, type) { console.log('ajax error'); console.log(xhr); console.log(type); } }); } }); let Bitcoin = Backbone.View.extend({ tagName: 'div', initialize: function () { _.bindAll(this, 'render'); this.model.bind('change', this.render); this.$btc = $('#btc'); }, render: function () { let btcdata = this.model.get('btcdata'); let title = 'High: $' + parseFloat(btcdata.highs.usd.toFixed(2)) + ' / Low $' + parseFloat(btcdata.lows.usd.toFixed(2)); this.$btc.removeClass(); this.$btc.addClass(btcdata.eclass); this.$btc.html(`$${parseFloat(btcdata.lastUSD.toFixed(2)) } / £${parseFloat(btcdata.lastGBP.toFixed(2))}` ); this.$btc.prop('title', title); } });