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.
这对改变图书馆是非常好的,如果你不需要知道哪个属性改变,只是事情发生了转变。