ctucx.git: smartie-pwa

[js] smarthome web-gui

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 
"use strict";

class Archive {
	constructor() {
		this.data = JSON.parse(localStorage.getItem("archive") || "{}");;
		this._loading = {};
		this._upToDate = {};
		this._subscribers = [];
	}

	finishedLoading() {
		return Object.keys(this._loading).length == 0;
	}

	subscribe(callback) {
		this._subscribers.push(callback);
		this._updateSubscribers();
	}

	_updateSubscribers() {
		for (let sub of this._subscribers) {
			sub();
		}
	}

	load(file) {
		if (!this.data[file] || !this._upToDate[file]) {
			this._loading[file] = true;
			fetch(`./archive/${file}.json`)
				.then(resp => resp.json())
				.then(data => {
					this.data[file] = data;
					this._upToDate[file] = true;
					localStorage.setItem("archive", JSON.stringify(this.data));
					delete this._loading[file];
					this._updateSubscribers();
				}).catch(e => {
					console.warn(e);
				});
		}
	}
}

export const archive = new Archive();