1
0
Fork 0

Fix saver bugs

upload-progress
Ambrose Chua 2021-05-23 23:49:31 +08:00
parent 7f274c0e10
commit 1da8e7af80
2 changed files with 27 additions and 11 deletions

View File

@ -2,7 +2,7 @@ import filesize from 'filesize';
class Log {
constructor(target, key, messages) {
this.key = key;
this.key = 'log:' + key;
this.target = target;
this.items = [];
@ -16,12 +16,12 @@ class Log {
}
localStorageLoad() {
const loaded = JSON.parse(window.localStorage.getItem('log' + this.key) || '[]');
const loaded = JSON.parse(window.localStorage.getItem(this.key) || '[]');
this.items.push(...loaded);
}
localStorageSave() {
window.localStorage.setItem('log' + this.key, JSON.stringify(this.items));
window.localStorage.setItem(this.key, JSON.stringify(this.items));
}
static renderItem(item) {

View File

@ -4,7 +4,7 @@ class Saver {
constructor(target, inputs, key='') {
this.target = target;
this.inputs = inputs;
this.key = '';
this.key = 'save:' + key;
this.limiter = new Limiter();
@ -12,18 +12,34 @@ class Saver {
this.input = this.input.bind(this);
this.save = this.save.bind(this);
this.loadState();
this.target.addEventListener('input', this.updateState);
this.updateState();
}
loadState() {
if (window.localStorage.getItem(this.key) !== null) {
this.target.checked = true;
} else {
this.target.checked = false;
}
this.updateBind();
}
updateState() {
if (this.target.checked) {
this.inputs.forEach(input => input.addEventListener('input', this.input));
this.save();
} else {
this.inputs.forEach(input => input.removeEventListener('input', this.input));
this.clear();
}
this.updateBind();
}
updateBind() {
if (this.target.checked) {
this.inputs.forEach(input => input.addEventListener('input', this.input));
} else {
this.inputs.forEach(input => input.removeEventListener('input', this.input));
}
}
input() {
@ -31,7 +47,7 @@ class Saver {
}
load() {
const values = JSON.parse(window.localStorage.getItem('save' + this.key) || '{}');
const values = JSON.parse(window.localStorage.getItem(this.key) || '{}');
for (const input of this.inputs) {
if (input.name in values) {
input.value = values[input.name];
@ -44,11 +60,11 @@ class Saver {
for (const input of this.inputs) {
values[input.name] = input.value;
}
window.localStorage.setItem('save' + this.key, JSON.stringify(values));
window.localStorage.setItem(this.key, JSON.stringify(values));
}
clear() {
window.localStorage.removeItem('save' + this.key);
window.localStorage.removeItem(this.key);
}
}
@ -58,7 +74,7 @@ saveInputs.forEach(saveInput => {
const inputNames = saveInput.dataset.save.split(',');
const inputs = inputNames.map(inputName => document.querySelector(`[name="${inputName}"]`));
const saver = new Saver(saveInput, inputs);
const saver = new Saver(saveInput, inputs, saveInput.dataset.save);
saver.load();
});