StoredMemory.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * This is used to store and retrieve values to/from Data Storage.
  3. * The value used in the constructor is merely the Default value. It is safe to assume that the correct value will be loaded immediately.
  4. * WARNING: IF YOU CHANGE THE TYPE OF VALUE A MEMORY STORES, YOU ALSO NEED A NEW ID. OR CHECKS. NEW ID IS EASIER.
  5. * Optionally: use listeners if you have to change value on the fly.
  6. */
  7. /// <reference path="../Modules/Memory.ts" />
  8. class StoredMemory<T> {
  9. private id : string;
  10. private value : T;
  11. private listeners : Array<Function> = [];
  12. public constructor (id : string, value : T) {
  13. this.id = id;
  14. this.value = value;
  15. Controls.Memory.registerMemory (this);
  16. }
  17. /**
  18. * For use exclusively by Controls.Memory. Do not invoke. Use storeValue instead.
  19. * @param {T} value
  20. */
  21. public setValueFromLocalStorageDoNotInvoke (value : T) {
  22. this.value = value;
  23. }
  24. public storeValue (value : T) {
  25. if (JSON.stringify(value) !== JSON.stringify(this.value)) {
  26. this.value = value;
  27. this.triggerListeners();
  28. }
  29. }
  30. public getValue () {
  31. return this.value;
  32. }
  33. public getId () {
  34. return this.id;
  35. }
  36. public addListener (listener : Function) {
  37. this.listeners.push(listener);
  38. }
  39. public triggerListeners () {
  40. for (var i = 0; i < this.listeners.length; i++) {
  41. this.listeners[i](this);
  42. }
  43. }
  44. }