JavaScript对象镜像/单向属性同步 [英] JavaScript Object Mirroring/One-way Property Syncing
问题描述
出于安全考虑,我需要一个镜像对象。即,如果我创建对象A,并浅层克隆A的副本并将其称为B,则只要A的属性发生更改,我希望B自动更新以反映更改,但不是相反。换句话说,单向属性同步。
For security purposes, I have a need for a "mirrored" object. i.e. if I create object A, and shallow-clone a copy of A and call it B, whenever a property of A changes, I hope to have B automatically update itself to reflect the changes, but not the other way around. In other words, one-way property syncing.
我的问题:我是否已经知道了解决方案?
My question: is there already a solution out in the wild that I'm not aware of?
考虑用observe-js实现一个库( https://github.com/polymer/observe-js ),但我想在继续之前我应该四处询问。谢谢。
Was thinking of implementing a library with observe-js (https://github.com/polymer/observe-js), but thought I should ask around before proceeding. Thanks.
推荐答案
假设您不需要支持IE8及更早版本,您可以使用getter在现代浏览器上执行此操作。
Assuming you don't need to support IE8 and earlier, you can use getters to do that on modern browsers.
function proxy(src) {
var p = {};
Object.keys(src).forEach(function(key) {
Object.defineProperty(p, key, {
get: function() {
return src[key];
}
});
});
return p;
}
var a = {
foo: "Original foo",
bar: "Original bar"
};
var b = proxy(a);
console.log(b.foo); // "Original foo"
a.foo = "Updated foo"; // Note we're writing to a, not b
console.log(b.foo); // "Updated foo"
这篇关于JavaScript对象镜像/单向属性同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!