added localStorage save and load (behind-the-scenes)
This commit is contained in:
parent
e4b8c62f81
commit
0f21c841f2
|
@ -34,6 +34,13 @@
|
||||||
|
|
||||||
// initialize the collection
|
// initialize the collection
|
||||||
this.records = Array.isArray(init) ? init : [];
|
this.records = Array.isArray(init) ? init : [];
|
||||||
|
// get stored records, merge as needed
|
||||||
|
if(this.store && localStorage) {
|
||||||
|
this._log("Initializing localStorage for " + this.store);
|
||||||
|
|
||||||
|
let existing = this._load() || [];
|
||||||
|
this.records = [...existing];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -71,6 +78,8 @@
|
||||||
|
|
||||||
return entry;
|
return entry;
|
||||||
});
|
});
|
||||||
|
// save to storage
|
||||||
|
this._save();
|
||||||
} else {
|
} else {
|
||||||
if (!entry.id) {
|
if (!entry.id) {
|
||||||
entry.id = Math.random().toString(36).substr(2, 9);
|
entry.id = Math.random().toString(36).substr(2, 9);
|
||||||
|
@ -78,6 +87,8 @@
|
||||||
|
|
||||||
this.records.push(entry);
|
this.records.push(entry);
|
||||||
|
|
||||||
|
// save to storage
|
||||||
|
this._save();
|
||||||
return entry;
|
return entry;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -160,12 +171,19 @@
|
||||||
this.records.splice(this.records.indexOf(item), 1);
|
this.records.splice(this.records.indexOf(item), 1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// save to storage
|
||||||
|
this._save();
|
||||||
|
|
||||||
// return records removed
|
// return records removed
|
||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
|
|
||||||
clear() {
|
clear() {
|
||||||
|
// erase records to empty array
|
||||||
this.records = [];
|
this.records = [];
|
||||||
|
|
||||||
|
// save to storage
|
||||||
|
this._save();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -175,10 +193,31 @@
|
||||||
return this.records.length;
|
return this.records.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
// save to localstorage
|
// save to localstorage
|
||||||
save() {
|
/**
|
||||||
if (this.storage) {
|
* save a record to storage if available
|
||||||
// check for localStorage
|
*
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @memberof Record
|
||||||
|
*/
|
||||||
|
_save() {
|
||||||
|
if (this.store && localStorage) {
|
||||||
|
localStorage.setItem(this.store, JSON.stringify(this.records));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* load records from storage if exists
|
||||||
|
*
|
||||||
|
* @private
|
||||||
|
*
|
||||||
|
* @returns {array} of loaded records
|
||||||
|
* @memberof Record
|
||||||
|
*/
|
||||||
|
_load() {
|
||||||
|
if (this.store && localStorage) {
|
||||||
|
return JSON.parse(localStorage.getItem(this.store)) || [];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue