DataModel.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import { EventDispatcher } from "../events/EventDispatcher";
  2. import DataModelEvent from "./DataModelEvent";
  3. export default class DataModel extends EventDispatcher
  4. {
  5. private propertys:Map<string,any>=new Map<string,any>();
  6. /**
  7. * 是否是新玩家
  8. */
  9. public isNewPlayer:boolean;
  10. constructor(){
  11. super();
  12. }
  13. /**
  14. * 游戏名称
  15. */
  16. public get gameName():string{
  17. return this.GetProperty("gameName");
  18. }
  19. public set gameName(value:string){
  20. this.SetProperty("gameName",value);
  21. }
  22. /**
  23. * 用户ID
  24. */
  25. public get userId():string{
  26. return this.GetProperty("userId");
  27. }
  28. public set userId(value:string){
  29. this.SetProperty("userId",value);
  30. }
  31. /**
  32. * 设置属性
  33. * @param key
  34. * @param value
  35. */
  36. public SetProperty(key:string,value:any):void{
  37. if(this.propertys.has(key)){
  38. let oldValue:any=this.propertys.get(key);
  39. if(oldValue==value){
  40. return;
  41. }
  42. }
  43. this.propertys.set(key,value);
  44. this.DispatchEvent(DataModelEvent.PROPERTY_CHANGED,key);
  45. }
  46. /**
  47. * 获取属性
  48. * @param key
  49. */
  50. public GetProperty(key:string):any{
  51. if(this.propertys.has(key)){
  52. return this.propertys.get(key);
  53. }
  54. return null;
  55. }
  56. /**
  57. * 清空游戏本地数据
  58. */
  59. ClearLocalData():void{
  60. localStorage.clear();
  61. }
  62. /**
  63. * 保存到本地
  64. */
  65. SaveToLoacl():void{
  66. var data:any=Array.from(
  67. this.propertys.entries()
  68. )
  69. .reduce((o, [key, value]) => {
  70. o[key] = value;
  71. return o;
  72. }, {})
  73. this.OnSaveToLocal(data);
  74. localStorage.setItem(this.gameName+"_"+this.userId,JSON.stringify(data));
  75. }
  76. protected OnSaveToLocal(data:any):void{
  77. }
  78. /**
  79. * 从本地读取数据
  80. */
  81. ReadByLocal():void{
  82. let jsonStr:string=localStorage.getItem(this.gameName+"_"+this.userId);
  83. if(!jsonStr){
  84. this.isNewPlayer=true;
  85. }else{
  86. try {
  87. let jsonData:any=JSON.parse(jsonStr);
  88. for (const key in jsonData) {
  89. if (Object.prototype.hasOwnProperty.call(jsonData, key)) {
  90. const element = jsonData[key];
  91. this.SetProperty(key,element);
  92. }
  93. }
  94. this.OnReadByLocal(jsonData);
  95. this.isNewPlayer=false;
  96. } catch (error) {
  97. console.log("读取本地数据失败")
  98. this.isNewPlayer=true;
  99. }
  100. }
  101. if(this.isNewPlayer){
  102. this.SetDefaultPropertys();
  103. }
  104. }
  105. protected OnReadByLocal(data:any):void{
  106. }
  107. /**
  108. * 设置默认属性
  109. */
  110. SetDefaultPropertys():void{
  111. }
  112. }