简体   繁体   English

如何在不触发观察者的情况下更改观察对象的值

[英]How to change value of an observed object without triggering it's observers

The question is pretty simple but seems like this is impossible with the current implementation of Object.observe. 这个问题很简单,但似乎对于Object.observe的当前实现是不可能的。 Imagine : 想象一下:

var obj = { foo: 1 }
Object.observe(obj, function (changes) {
    console.log(changes)
})
obj.foo = 2

This will log an object with the changes I've made, as expected. 如预期的那样,这将记录我所做的更改的对象。 So the question is how can I change the property without this side effect? 所以问题是,如何在没有副作用的情况下更改属性?

Well, one of the goals of Object.observe design is to catch absolutely all changes of the object, any time. 好吧,Object.observe设计的目标之一就是随时随地捕获对象的所有变化。

Answer depends on what you actually need. 答案取决于您的实际需求。 Code below, for example, will not cause change events on the object: 例如,下面的代码将不会导致对象发生更改事件:

var obj = { foo: [1] }
Object.observe(obj, function (changes) {
    console.log(changes)
})
obj.foo[0] = 2

As technically object itself will not change. 从技术上讲,对象本身不会改变。

One of possible options is to provide your own, patched Object.observe implementation that will notify observers only when some flag is on. 一种可能的选择是提供您自己的经过修补的Object.observe实现,该实现仅在某些标志打开时才通知观察者。

Or instead, to use some higher level idiom like pubsub mechanism where you can manage 'change' events emissions. 或者相反,使用诸如pubsub机制之类的更高层次的习惯用法,您可以在其中管理“变更”事件的发出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM