经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
javascript Proxy 代理模式深度监听对象、数组变化
来源:cnblogs  作者:大花猫花大  时间:2020/6/29 15:29:27  对本文有异议
/**
 * 对象、数组变化监听(增删改)
 * @author w-bing
 * @date 2020-04-22
 * @param {Object} obj
 * @param {Function} cb
 * @return {Proxy}
 */
function deepProxy(obj, cb) {

	if (typeof obj === 'object') {

		for (let key in obj) {
			if (typeof obj[key] === 'object') {
				obj[key] = deepProxy(obj[key], cb);
			}
		}

	}

	return new Proxy(obj, {

		/**
		 * @param {Object, Array} target 设置值的对象
		 * @param {String} key 属性
		 * @param {any} value 值
		 * @param {Object} receiver this
		 */
		set: function (target, key, value, receiver) {

			if (typeof value === 'object') {
				value = deepProxy(value, cb);
			}

			let cbType = target[key] == undefined ? 'create' : 'modify';

			//排除数组修改length回调
			if (!(Array.isArray(target) && key === 'length')) {
				cb(cbType, { target, key, value });
			}
			return Reflect.set(target, key, value, receiver);

		},
		deleteProperty(target, key) {
			cb('delete', { target, key });
			return Reflect.deleteProperty(target, key);
		}

	});

}


// 数组测试
let a = deepProxy([], (type, data) => {
	console.log(type, data);
});

a.push(1)
a.push({ a: 1 })

// 对象测试
let b = deepProxy({}, (type, data) => {
	console.log(type, data);
});

b.name = '大花猫花大';
b.info = {
	age: 10,
	data: {
		data: {
			data: {
				text: 1
			}
		}
	}
}

delete b.info.age;

  

原文链接:http://www.cnblogs.com/aiv367/p/12753340.html

 友情链接: NPS