import { EventDispatcher } from "../events/EventDispatcher"; import DataModelEvent from "./DataModelEvent"; export default class DataModel extends EventDispatcher { private propertys:Map=new Map(); /** * 是否是新玩家 */ public isNewPlayer:boolean; constructor(){ super(); } /** * 游戏名称 */ public get gameName():string{ return this.GetProperty("gameName"); } public set gameName(value:string){ this.SetProperty("gameName",value); } /** * 用户ID */ public get userId():string{ return this.GetProperty("userId"); } public set userId(value:string){ this.SetProperty("userId",value); } /** * 设置属性 * @param key * @param value */ public SetProperty(key:string,value:any):void{ if(this.propertys.has(key)){ let oldValue:any=this.propertys.get(key); if(oldValue==value){ return; } } this.propertys.set(key,value); this.DispatchEvent(DataModelEvent.PROPERTY_CHANGED,key); } /** * 获取属性 * @param key */ public GetProperty(key:string):any{ if(this.propertys.has(key)){ return this.propertys.get(key); } return null; } /** * 清空游戏本地数据 */ ClearLocalData():void{ localStorage.clear(); } /** * 保存到本地 */ SaveToLoacl():void{ var data:any=Array.from( this.propertys.entries() ) .reduce((o, [key, value]) => { o[key] = value; return o; }, {}) this.OnSaveToLocal(data); localStorage.setItem(this.gameName+"_"+this.userId,JSON.stringify(data)); } protected OnSaveToLocal(data:any):void{ } /** * 从本地读取数据 */ ReadByLocal():void{ let jsonStr:string=localStorage.getItem(this.gameName+"_"+this.userId); if(!jsonStr){ this.isNewPlayer=true; }else{ try { let jsonData:any=JSON.parse(jsonStr); for (const key in jsonData) { if (Object.prototype.hasOwnProperty.call(jsonData, key)) { const element = jsonData[key]; this.SetProperty(key,element); } } this.OnReadByLocal(jsonData); this.isNewPlayer=false; } catch (error) { console.log("读取本地数据失败") this.isNewPlayer=true; } } if(this.isNewPlayer){ this.SetDefaultPropertys(); } } protected OnReadByLocal(data:any):void{ } /** * 设置默认属性 */ SetDefaultPropertys():void{ } }