Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to observe all object property changes?

For arrays I know you can do something like this:

function() {
}.observes("array.@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?

like image 250
JJJ Avatar asked Mar 13 '14 19:03

JJJ


People also ask

How do you list all properties of an object?

To get all own properties of an object in JavaScript, you can use the Object. getOwnPropertyNames() method. This method returns an array containing all the names of the enumerable and non-enumerable own properties found directly on the object passed in as an argument. The Object.

How do you check if an object has properties?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How do you change the properties of an object?

To change the value of an existing property of an object, specify the object name followed by: a dot, the name of the property you wish to change, an equals sign, and the new value you wish to assign.


1 Answers

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.

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

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));
        });
      }
    }); 
  }
});

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

like image 153
chopper Avatar answered Sep 20 '22 00:09

chopper