Observing changes on any field in bound model in Controller

Go To StackoverFlow.com

2

I'm binding a model to my Controller and I'd like to observe any changes to its fields so I can reload some data and refresh a view.

Right now I have something really non-DRY like this:

goalController = Ember.Object.create({
  ...
  recompute: function() { save model, load recomputed data from server }
  ...
  nameChanged: function() { this.recompute() }.observes('content.name'),
  incomeChanged: function() { this.recompute() }.observes('content.income')  
});

Is there a Ember-y way of doing this?

2012-04-05 01:32
by outside2344


7

You can setup multiple observers at a time, so you could rewrite your example like so:

goalController = Ember.Object.create({

    goalUpdated: function() {
        // do your thing
    }.observes("content.name", "content.income")

});

Here's a fiddle: http://jsfiddle.net/rlivsey/upZDU/

2012-04-05 12:54
by rlivsey
You should also be able to write it as:

``` goalController = Ember.Object.create({

goalUpdated: function() {
    // do your thing
}.observes("content.{name,income}")

}); `` - srt32 2015-04-02 18:40

That would work @str32 but it may get really ugly for models with 5+ properties to watch. I did create an alarm property inside the model, and an observer hat toggles the alarm, inside the model, over all the properties that I wanted to observe from the controller. Finally a single observe over model.alarm. Still ugly, but the controller doesn't need to now the internals of the model under this scenario - robertodecurnex 2015-05-15 17:35
Observing properties of model in controller has one side effect. Everytime your controller's content (model) is changed (swapped for another one) your observer is fired. E.g. if you observes changes for "content.innerObject.name" if any of content or content's innerObject or content's innerObject's name changes, your observer fires - petriq 2018-07-12 13:48
Ads