| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110 |
- import { DataSystem } from "./DataSystem";
- /**
- * 数据对象
- * @description 请通过DataSystem.createData来实例化对象,否则将无法使用DataSystem.watch
- * @author 袁浩
- */
- export class Data {
- protected proxy: any;
- protected arrayKey: Map<any, PropertyKey> = new Map<any, PropertyKey>();
- public constructor() {
- return this.initProxy();
- }
- protected initProxy() {
- this.proxy = new Proxy(this, { set: this.setProperty.bind(this), deleteProperty: this.deleteProperty.bind(this) });
- return this.proxy;
- }
- protected setProperty<T>(target: T, p: PropertyKey, value: any, receiver: any): boolean {
- target[p] = value;
- if (Array.isArray(value)) {
- let proxy = new Proxy(value, { set: this.setArrayProperty.bind(this) });
- target[p] = proxy;
- this.arrayKey.set(proxy, p);
- }
- p != 'proxy' && DataSystem.onPropertyChange(this.proxy, p);
- return true;
- }
- protected setArrayProperty<T>(target: T, p: PropertyKey, value: any, receiver: any): boolean {
- target[p] = value;
- if (this.arrayKey.has(receiver)) {
- DataSystem.onPropertyChange(this.proxy, this.arrayKey.get(receiver));
- }
- return true;
- }
- protected deleteProperty<T>(target: T, p: PropertyKey): boolean {
- delete target[p];
- DataSystem.onPropertyChange(this, p);
- return true;
- }
- /**
- * 设值
- * @param key
- * @param value
- */
- public set(key: PropertyKey, value: any) {
- this[key] = value;
- }
- /**
- * 取值
- * @param key
- * @returns
- */
- public get(key: PropertyKey): any {
- return this[key];
- }
- /**
- * 判断是否有属性
- * @param key
- * @returns
- */
- public has(key: PropertyKey): boolean {
- return this[key] !== undefined;
- }
- /**
- * 拷贝数据
- * @param source 数据源
- */
- public copy(source: any, deleteOld: boolean = false) {
- if (deleteOld) {
- let obj = this.object;
- for (let key in obj) {
- if (source[key] === undefined) {
- delete this[key];
- }
- }
- }
- for (let key in source) {
- this.copyOne(key, source);
- }
- }
- protected copyOne(key: string, source: any) {
- this[key] = source[key];
- }
- /**
- * 基础数据对象
- */
- public get object() {
- var result: any = {};
- for (var key in this) {
- let value = this[key];
- if (
- key != "object" &&
- key != "proxy" &&
- key != "arrayKey" &&
- typeof this[key] != "function"
- ) {
- if (value instanceof Data) {
- result[key] = value.object;
- }
- else {
- result[key] = value;
- }
- }
- }
- return result;
- }
- private toJSON() {
- return JSON.stringify(this.object);
- }
- }
|