本文介绍了为什么不推荐使用Object.observe()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有替代方法吗?
还有另一种方法可以在对象中进行更改检测吗?
Is there another way to do change detection in object?
有代理方法,但任何人都可以告诉我如何使用代理实现此目的:
There is the Proxy method, but can anyone tell me how can I achieve this using Proxy:
var obj = {
foo: 0,
bar: 1
};
Object.observe(obj, function(changes) {
console.log(changes);
});
obj.baz = 2;
// [{name: 'baz', object: <obj>, type: 'add'}]
obj.foo = 'hello';
// [{name: 'foo', object: <obj>, type: 'update', oldValue: 0}]
推荐答案
你可以通过getter和setter实现这一点。
You can achieve this with getters and setters.
var obj = {
get foo() {
console.log({ name: 'foo', object: obj, type: 'get' });
return obj._foo;
},
set bar(val) {
console.log({ name: 'bar', object: obj, type: 'set', oldValue: obj._bar });
return obj._bar = val;
}
};
obj.bar = 2;
// {name: 'bar', object: <obj>, type: 'set', oldValue: undefined}
obj.foo;
// {name: 'foo', object: <obj>, type: 'get'}
或者,在支持Proxies的浏览器中,您可以编写更通用的解决方案。
Alternatively, in a browser with support for Proxies, you can write a more generic solution.
var obj = {
foo: 1,
bar: 2
};
var proxied = new Proxy(obj, {
get: function(target, prop) {
console.log({ type: 'get', target, prop });
return Reflect.get(target, prop);
},
set: function(target, prop, value) {
console.log({ type: 'set', target, prop, value });
return Reflect.set(target, prop, value);
}
});
proxied.bar = 2;
// {type: 'set', target: <obj>, prop: 'bar', value: 2}
proxied.foo;
// {type: 'get', target: <obj>, prop: 'bar'}
这篇关于为什么不推荐使用Object.observe()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!