简体   繁体   English

从Object.observe过渡

[英]Transitioning away from Object.observe

I've been using Object.observe() as part of a nw.js project that is now transitioning from nw.js v.0.12.3 to latest. 我一直在将Object.observe()用作nw.js项目的一部分,该项目现在正从nw.js v.0.12.3过渡到最新版本。

I have code like this: 我有这样的代码:

..(myclass)..
data: { a:0, b:42 },
setupHandlers: function () {
    Object.observe(this.data, changes => this.draw());
},
draw: function () { .. }

My initial conversion looks like: 我的初始转换如下:

data: {_a: 0, _b: 42},
get a() { return this._a; }
set a(val) { this.data._a = val; this.draw(); } 
get b() { return this._b; }
set b(val) { this.data._b = val; this.draw(); } 

and then change every place that wrote to data ( myobj.data.a = 1 ) to instead write to the object ( myobj.a = 1 ), thus using the setter. 然后将写入数据的每个位置( myobj.data.a = 1 )更改为写入对象( myobj.a = 1 ),从而使用setter。

It's a very labor-intensive conversion, is there an easier way? 这是一个非常劳动密集型的转换,有没有更简单的方法?

We ended up using Proxy to catch attribute assignment: 我们最终使用Proxy来捕获属性分配:

const shallow_observer = function (obj, fn) {
    return new Proxy(obj, {
        set(target, name, val) {
            target[name] = val;
            if (fn) fn(target, name, val);
            return true;
        }
    });
};

which allowed us to do: 这使我们能够:

data: { a:0, b:42 },
setupHandlers: function () {
    this.data = shallow_observer(this.data, (data, field, value) => this.draw());
},
draw: function () { .. }

We have a deep_observer function too (which is much more complex), that detects changes in a nested data structure, but the shallow_observer was sufficient for all our use-cases. 我们也有一个deep_observer函数(这个函数要复杂得多),它检测嵌套数据结构中的更改,但是shallow_observer对于我们的所有用例都是足够的。

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

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