local-storage.js 839 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. let storage = window.localStorage;
  2. export class LocalStorage {
  3. init(prefix) {
  4. this._prefix = prefix;
  5. this._watchers = [];
  6. window.addEventListener('storage', (e) => {
  7. let newValueJson = JSON.parse(e.newValue);
  8. this._watchers.forEach(function(watcher) {
  9. if (watcher.key === e.key && e.oldValue !== e.newValue) {
  10. watcher.callback(newValueJson);
  11. }
  12. });
  13. });
  14. }
  15. set(key, value) {
  16. storage.setItem(this._prefix + key, JSON.stringify(value));
  17. }
  18. get(key) {
  19. let itemString = storage.getItem(this._prefix + key);
  20. if (itemString) {
  21. return JSON.parse(itemString);
  22. } else {
  23. return null;
  24. }
  25. }
  26. watch(key, callback) {
  27. this._watchers.push({
  28. key: this._prefix + key,
  29. callback: callback
  30. });
  31. }
  32. }
  33. export default new LocalStorage();