Memory.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /// <reference path="../../Version.ts" />
  2. module Controls.Memory {
  3. let versionSet = false;
  4. let settingsVersion : Array<number> = Version.currentVersion;
  5. let versionId = "Version";
  6. let memoryPrefix = "obelisk_";
  7. let memories : {[id : string] : StoredMemory<any>} = {};
  8. export function getValue (id : string, defValue : any) {
  9. try {
  10. let storage = localStorage.getItem(memoryPrefix + id);
  11. return storage == undefined ? defValue : JSON.parse(storage);
  12. } catch (e) {
  13. // no localStorage
  14. console.error("[MEMORY] Can't use localStorage!");
  15. return defValue;
  16. }
  17. }
  18. export function setValue (id : string, value : any) {
  19. try {
  20. localStorage.setItem(memoryPrefix + id, JSON.stringify(value));
  21. } catch (e) {
  22. console.error("[MEMORY] Can't use localStorage!");
  23. }
  24. if (!versionSet) {
  25. versionSet = true;
  26. settingsVersion = getValue(versionId, Version.currentVersion);
  27. setValue(versionId, Version.currentVersion);
  28. }
  29. // TODO: Figure out why settingsVersion exists.
  30. if (settingsVersion == undefined) {}
  31. }
  32. export function registerMemory (mem : StoredMemory<any>) {
  33. if (memories[mem.getId()] != undefined) {
  34. console.error("[Controls.Memory] Memory already registered on id " + mem.getId(), "Old:", memories[mem.getId()], "New:", mem);
  35. } else {
  36. memories[mem.getId()] = mem;
  37. mem.setValueFromLocalStorageDoNotInvoke(getValue(mem.getId(), mem.getValue()));
  38. let updateF = () => {
  39. Controls.Memory.setValue(mem.getId(), mem.getValue());
  40. }
  41. mem.addListener(updateF);
  42. updateF();
  43. }
  44. }
  45. }