1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
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())
});
|