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

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

问题描述

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

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).

或者,您可以将逗号分隔的属性列表传递给 observes.如果您的对象上有很多属性,这可能会很长,但会起作用.

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 帖子 给出了以下答案:

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 以保持代码干燥.

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

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

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