使用setPath观察余烬对象的所有更改

Observe all changes to an ember object with setPath

本文关键字:对象 setPath 观察 余烬 使用      更新时间:2023-09-26

在emberJS中,我有一个模型,它具有一个名为style的对象属性。我可以使用test.setPath('style.a')设置它的属性。我正在尝试观察样式对象,但我的观察回调没有启动。

你可以在这里看到代码。

这种对Ember观察者工作方式的基本误解是一个常见的错误。在您的示例中,您的视图test:中有以下内容

...
style : Ember.Object.create({
    a:4,
    b:2
}),
setStyle : function(key, val){
    var style = this.get('style');
    style[key] = val;
    this.set('style', style);        
},
...

test.style属性指向Ember.Object,而test.setStyle()正在更改该Ember.Object上给定属性的值。一个常见的错误是认为将属性重置为同一对象会调用其上的任何观察者,就像您使用以下行一样:this.set('style', style)。恩,这不是Ember观察员的工作方式。当属性的实际值发生变化时,Ember中的观察程序会自动启动。将style属性设置为自身不会更改style所指向的对象,因此也不会更改属性的值(实际上,该代码什么都不做)。在这种情况下,您似乎需要手动告诉Ember style属性已经更改。您可以通过调用notifyPropertyChange()来完成此操作。

查看以下setStyle的修改代码:

setStyle : function(key, val){
    var style = this.get('style');
    style.set(key, val); // You should always use `.get()` and `.set()`
    this.notifyPropertyChange('style');
}

这将导致你的观察者开火。