StoredVariable.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. interface StoredVariableOptions<T> {
  2. id : string;
  3. value : T;
  4. }
  5. /**
  6. * StoredVariables are the only thing that gets stored on a Save/Reload.
  7. * It's only allowed to have StoredVariables that are either primitive or simple objects.
  8. */
  9. class StoredVariable<T> {
  10. public id : string;
  11. public value : T;
  12. public defValue : T;
  13. public constructor (options : StoredVariableOptions<T>) {
  14. this.id = options.id;
  15. this.value = options.value;
  16. this.defValue = this.value;
  17. StoredVariable.registerVariable(this);
  18. }
  19. public reset () {
  20. this.value = this.defValue;
  21. }
  22. public updateFromObject (obj : T) {
  23. this.value = obj;
  24. }
  25. public exportAsObject () {
  26. return this.value;
  27. }
  28. private static storedVariables : {[id : string] : StoredVariable<any>} = {};
  29. public static registerVariable (variable : StoredVariable<any>) {
  30. if (StoredVariable.storedVariables[variable.id] == undefined) {
  31. StoredVariable.storedVariables[variable.id] = variable;
  32. } else {
  33. console.warn("[StoredVariable] " + variable.id + " already defined. Ignoring:", variable);
  34. }
  35. }
  36. public static getVariable (id : string) {
  37. return StoredVariable.storedVariables[id];
  38. }
  39. public static getVariables () : Array<StoredVariable<any>>{
  40. let list = [];
  41. for (let key in StoredVariable.storedVariables) {
  42. list.push(StoredVariable.storedVariables[key]);
  43. }
  44. return list;
  45. }
  46. public static exportAsObject () : {[id : string] : any} {
  47. let list = {};
  48. for (let key in StoredVariable.storedVariables) {
  49. list[key] = StoredVariable.storedVariables[key].value;
  50. }
  51. return list;
  52. }
  53. public static updateFromObject (obj : {[id : string] : any}) {
  54. for (let key in StoredVariable.storedVariables) {
  55. if (obj[key] != undefined) {
  56. StoredVariable.storedVariables[key].updateFromObject(obj[key]);
  57. } else {
  58. StoredVariable.storedVariables[key].reset();
  59. }
  60. }
  61. }
  62. }