Skip to content

Instantly share code, notes, and snippets.

@ttu
Created August 4, 2017 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttu/427d817742ccea339d7c9cd8833a87ce to your computer and use it in GitHub Desktop.
Save ttu/427d817742ccea339d7c9cd8833a87ce to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Fake JSON Server</title>
<style type="text/css">
[v-cloak] {
display: none;
}
.sensor-data {
padding-bottom: 15px;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<h3>Sensors:</h3>
<div v-for="item in sensors">
<sensor-data class="sensor-data" v-bind:info="item"></sensor-data>
</div>
</div>
</body>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/superagent/3.5.2/superagent.min.js"></script>
<script>
var SensorComponent = Vue.extend({
template: `
<div>
<div>MAC: {{ info.mac }}</div>
<div>Temperature: {{ info.data.temperature }}</div>
<div>Humidity: {{ info.data.humidity }}</div>
<div>Pressure: {{ info.data.pressure }}</div>
<div>Time: {{ info.timestamp }}</div>
</div>
`,
props: ['info']
})
Vue.component('sensor-data', SensorComponent)
var app = new Vue({
el: '#app',
data: {
sensors: [] }
});
const request = window.superagent;
request
.get('http://localhost:57602/api/sensors')
.end((err, resp) => {
app.sensors = resp.body;
});
const webSocket = new WebSocket("ws://localhost:57602/ws");
webSocket.onmessage = (evt) => {
const updateInfo = JSON.parse(evt.data);
if (updateInfo.method == "DELETE")
return;
request
.get(`http://localhost:57602${updateInfo.path}`)
.end((err, resp) => {
const newData = resp.body;
var indexOfItem = app.sensors.findIndex(x => x.mac == newData.mac);
if (indexOfItem > 0)
// app.sensors[indexOfItem] = newData;
Vue.set(app.sensors, indexOfItem, newData)
else
app.sensors.push(newData);
});
};
webSocket.onopen = () => { console.log('open'); };
webSocket.onclose = () => { console.log('closed'); };
webSocket.onerror = (evt) => { console.log(evt.data); };
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment