如何观察所有对象的属性变化? [英] How to observe all object property changes?

查看:138
本文介绍了如何观察所有对象的属性变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于数组,我知道你可以这样做:

For arrays I know you can do something like this:

function() {
}.observes("array.@each")

我所做的是将对象转换为数组并观察属性有一个@each,但是有没有更好的方法来观察对象的所有属性更改,而不将其转换成数组?

What I did was convert the object into an array and observe the properties with a @each, but is there a better way to observe object all property changes without converting it into an array?

推荐答案

你可以观察 isDirty ,看看是否有任何对象的值自上次保存以来已被修改(如果您使用的是Ember Data)。

You can observe isDirty to see if any of the object's values have been modified since last save (if you are using Ember Data).

或者,您可以将逗号分隔的属性列表传递给观察。如果你的对象有很多属性,但是可以工作,这可能很长。

Alternatively you can pass a comma separated list of properties to observes. This might be long if you have a lot of properties on your object, but will work.

第三种方法可能是覆盖 setUnknownProperty() 并设置属性,脏标志(或执行您可能需要的任何操作。

A third approach could be to override setUnknownProperty() and set a property, a 'dirty flag' (or perform any action you may want in there.

还有一个 SO SO ,提供以下答案:

There's also an old SO post that gives the following answer:

App.WatchedObject = Ember.Object.extend({
  firstProp: null,
  secondProp: "bar",

  init: function(){
    this._super();
    var self = this;
    Ember.keys(this).forEach(function(key){
      if(Ember.typeOf(self.get(key)) !== 'function'){
        self.addObserver(key, function(){
          console.log(self.get(key));
        });
      }
    }); 
  }
});

你可能把它拆分成一个Mixin来记录p你的代码DRY。

You could probably split this out into a Mixin to keep your code DRY.

这篇关于如何观察所有对象的属性变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆