StateManager.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { _decorator, Label, Node } from 'cc';
  2. import { Singleton } from './Singleton';
  3. import { Constants } from '../../data/Constants';
  4. import { userIns } from '../../data/UserData';
  5. import { Utils } from '../../utils/Utils';
  6. const { ccclass, property } = _decorator;
  7. @ccclass('StateManager')
  8. class StateManager extends Singleton{
  9. //存储状态字段与 UI 组件的绑定关系
  10. private uiBindings: Map<string, Label[]> = new Map();
  11. /**
  12. * 注册UI组件
  13. * @param field 注册的key uiName
  14. * @param label 具体的文本
  15. */
  16. public registerUI(field: string, label: Label|any): void {
  17. if(!this.uiBindings.has(field)) {
  18. this.uiBindings.set(field, []);
  19. }
  20. //将UI组件添加到绑定列表
  21. let uiArr:Array<any> = this.uiBindings.get(field);
  22. if(!uiArr.includes(label)){
  23. uiArr.push(label);
  24. }
  25. //初始化UI显示
  26. this.updateSingleUI(field, label);
  27. }
  28. /**
  29. * 全局更新所有绑定该字段
  30. * @param field 注册的key uiName
  31. */
  32. public updateAllUI(field: string): void {
  33. let labels:Array<any> = this.uiBindings.get(field);
  34. if (labels) {
  35. labels.forEach(label => {
  36. this.updateSingleUI(field, label);
  37. });
  38. }
  39. }
  40. /**
  41. * 更新单个UI组件
  42. * @param field
  43. * @param label
  44. */
  45. private updateSingleUI(field: string, com: Label|any): void {
  46. if(field == Constants.gold){//金币数量
  47. com.string = `${Utils.numberToString(userIns.data.gold)}`;
  48. }else if(field == Constants.diamond){//钻石数量
  49. com.string = `${Utils.numberToString(userIns.data.diamond)}`;
  50. }else if(field == Constants.levelTask){//任务数据变化
  51. }
  52. }
  53. }
  54. //全局单例
  55. export const stateMgr = StateManager.ins();