使用JavaScript观察对象更改

Watching for changes to an object's property has always been a much sought after task; many shims have been used over the years to listen to object changes.  These days we have better methods for listening to object changes:  the Proxy API.  Sindre Sorhus has created on-change, a tiny JavaScript tool that allows you to listen for changes on JavaScript objects and arrays!

一直以来,关注对象属性的更改一直是人们追求的目标。 多年来,已经使用了许多垫片来监听对象的变化。 如今,我们有更好的方法来监听对象更改:Proxy API。 Sindre Sorhus创建了on-change ,这是一个微型JavaScript工具,可让您侦听JavaScript对象和数组上的变化!

不断变化JavaScript (on-change JavaScript)

Since the on-change code is so tiny, here it is in its full glory:

由于不断变化的代码是如此之小,因此这里充满了荣耀:


'use strict';

module.exports = (object, onChange) => {
	const handler = {
		get(target, property, receiver) {
			try {
				return new Proxy(target[property], handler);
			} catch (err) {
				return Reflect.get(target, property, receiver);
			}
		},
		defineProperty(target, property, descriptor) {
			onChange();
			return Reflect.defineProperty(target, property, descriptor);
		},
		deleteProperty(target, property) {
			onChange();
			return Reflect.deleteProperty(target, property);
		}
	};

	return new Proxy(object, handler);
};


The onChange function returns a proxy which you'll use to make any object changes.

onChange函数返回一个代理,您将使用该代理进行任何对象更改。

使用零钱 (Using on-change)

Pass onChange the object you'd like to spy on and a change handler function:

传递onChange您想要监视的对象和一个更改处理函数:


let j = {
    a: 1
};

// Upon change, save to server
let changeable = onChange(j, () => save(j));


Then use that Proxy to change properties and get notified of changes:

然后使用该代理更改属性并获得更改通知:



// Make a change that would trigger changes
changeable.a = 2;

// save() is triggered!

// j.a === 2


Note that the original object's values also change -- that's the beauty of Proxy!  Also note that on-change doesn't tell you which property changed; the use case, as Sindre describes, is saving an object (to server, etc.) when any part of an object changes.  You could also use ti for a small library with a render function, re-rendering the content whenever a property changed!

请注意,原始对象的值也会更改-这就是Proxy的美! 还要注意,按变化并不能告诉您哪个属性已变化; 正如Sindre所描述的,用例是在对象的任何部分发生更改时将对象保存到服务器等。 您也可以将ti用于具有渲染功能的小型库,每当属性更改时就重新渲染内容!

This on-change library is really nice if you don't need to know which property changed, just that something changed.

这对改变图书馆是非常好的,如果你不需要知道哪个属性改变,只是事情发生了转变。

翻译自: https://davidwalsh.name/watch-object-changes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值