RenderReactiveHandler.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import { Component } from "cc";
  2. export function isObject(value: unknown): value is Record<any, any> {
  3. return value !== null && typeof value === 'object';
  4. }
  5. const hasOwnProperty = Object.prototype.hasOwnProperty
  6. /** 是否自身上存在属性 */
  7. export function hasOwn(val: object, key: string | number | symbol): key is keyof typeof val {
  8. if (val instanceof Component) {
  9. return key in val;
  10. }
  11. return hasOwnProperty.call(val, key);
  12. }
  13. /** 比较值是否变化了,考虑NaN;如果是对象直接认为改变了 */
  14. export function hasChanged(value: any, oldValue: any): boolean {
  15. let type = typeof value;
  16. if (type === "object") return true;
  17. return !Object.is(value, oldValue);
  18. }
  19. export class RenderReactiveHandler {
  20. constructor(reactiveTarget?: object) {
  21. this.reactiveTarget = reactiveTarget;
  22. }
  23. /**需要作出反应的对象 */
  24. private reactiveTarget: object = null;
  25. /**
  26. *
  27. * @param target 被代理的对象
  28. * @param prop 被代理的对象的属性名
  29. * @param value 被代理的对象的属性值
  30. * @param receiver 代理对象
  31. * @returns
  32. */
  33. set(target: object, prop: string | symbol, value: any, receiver: any): boolean {
  34. let oldValue = Reflect.get(target, prop);
  35. let hadKey = hasOwn(target, prop);
  36. let result = Reflect.set(target, prop, value);
  37. if (!hadKey || hasChanged(value, oldValue)) {
  38. if (prop == "angle" || prop == 'scale' || prop == "position" || prop == "_renderFlag") return;
  39. if (prop == 'activeInHierarchy') {
  40. console.warn(target);
  41. }
  42. // 属性变化
  43. this.reactiveTarget && (Reflect.set(this.reactiveTarget, prop, value));
  44. }
  45. return result
  46. }
  47. apply() {
  48. console.warn(arguments)
  49. }
  50. get(target: object, prop: string | symbol, receiver: any): any {
  51. if (prop === '__raw__') {
  52. return target;
  53. }
  54. else if (prop === '__isReactive__') {
  55. return true;
  56. }
  57. let rawValue = Reflect.get(target, prop);
  58. return rawValue;
  59. }
  60. deleteProperty(target: object, prop: string | symbol): boolean {
  61. let hadKey = hasOwn(target, prop);
  62. let oldValue = target[prop];
  63. let result = Reflect.deleteProperty(target, prop);
  64. if (result && hadKey) {
  65. //trigger(target, prop, void 0, oldValue);
  66. }
  67. return result;
  68. }
  69. }