MyComponent.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Learn TypeScript:
  2. // - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
  3. // Learn Attribute:
  4. // - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
  5. // Learn life-cycle callbacks:
  6. // - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html
  7. const { ccclass, property } = cc._decorator;
  8. @ccclass
  9. export default class MyComponent extends cc.Component {
  10. _eventMap = [];
  11. onLoad() {
  12. // super.onLoad();
  13. this.devicesFit();
  14. }
  15. //注册事件
  16. regEvent(type, callback, target = null, once = null) {
  17. cc.systemEvent.on(type, callback, target, once);
  18. this._eventMap.push({
  19. type: type,
  20. callback: callback,
  21. target: target,
  22. once: once
  23. });
  24. }
  25. regEventOnce(type, callback, target = null) {
  26. cc.systemEvent.once(type, callback, target);
  27. this._eventMap.push({
  28. type: type,
  29. callback: callback,
  30. target: target,
  31. once: null
  32. });
  33. }
  34. // 机型适配 子类重载
  35. devicesFit() {
  36. }
  37. onDestroy() {
  38. // super.onDestroy();
  39. for (let i = 0; i < this._eventMap.length; i++) {
  40. let data = this._eventMap[i];
  41. cc.systemEvent.off(data.type, data.callback, data.target);
  42. }
  43. delete this._eventMap;
  44. this.unscheduleAllCallbacks();
  45. }
  46. }
  47. export function Singleton<T>() {
  48. class Singleton {
  49. private static minst: any = null;
  50. public static get Inst(): T {
  51. if ((<any>this).minst == null) {
  52. (<any>this).minst = new (<any>this)()
  53. (<any>this).init()
  54. }
  55. return (<any>this).minst
  56. }
  57. constructor() {
  58. }
  59. public disp() {
  60. (<any>this).minst = null
  61. }
  62. }
  63. return Singleton
  64. }