var app = {} // Device model app.Device = Backbone.Model.extend({ idAttribute: 'device_id' }); // Devices Collection app.Devices = Backbone.Collection.extend({ idAttribute: 'device_id', url: 'data', model: app.Device, parse: function(resp) { return resp.devices; } }); // Device view app.DeviceView = Backbone.View.extend({ className: 'device', viewTemplate: _.template($('#device-template').html()), editTemplate: _.template($('#edit-device-template').html()), events: { 'click .edit': 'onEdit', 'submit form': 'onSave', 'click .cancel': 'onCancel' }, initialize: function() { this.listenTo(this.model, 'change', this.render); this.template = this.viewTemplate; }, compute: function() { const device_id = this.model.attributes.device.device_id; let name = localStorage.getItem("device_id=" + device_id + ".name"); if (name == null) { name = "A beautiful flower"; } const template_vars = { name: name, water_level: Math.round(this.model.attributes.device.water_level * 100) + "%", current_value: this.model.attributes.device.current_value, last_updated: new Date(this.model.attributes.device.last_updated).toLocaleString(), last_watered: new Date(this.model.attributes.device.last_watered).toLocaleString() }; return template_vars; }, render: function() { this.$el.html(this.template(this.compute())); return this; }, onEdit: function(e) { this.template = this.editTemplate; this.render(); this.$el.html(this.editTemplate(this.compute())); }, onSave: function(e) { e.preventDefault(); const new_name = e.target.name.value; const device_id = this.model.attributes.device.device_id; let name = localStorage.setItem("device_id=" + device_id + ".name", new_name); this.$el.html(this.template(this.compute())); this.template = this.viewTemplate; this.render(); }, onCancel: function(e) { this.template = this.viewTemplate; this.render(); } }); // The main app app.AppView = Backbone.View.extend({ el: "#content", initialize: function() { app.devices = new app.Devices(); app.devices.on('add', this.addOneDevice, this); app.devices.on('reset', this.addAllDevices, this); this.refresh(); }, refresh: function() { app.devices.fetch({ success: function() { } }); let self = this; setTimeout(function() { self.refresh(); }, 300000); }, addOneDevice: function(device) { var view = new app.DeviceView({model: device}); this.$el.append(view.render().el); }, addAllDevices: function() { this.$el.html(''); app.devices.each(this.addOneDevice, this); } }); $(document).ready(function() { $("#content").html(new app.AppView()) });