5
votes

I want to run some view code when the model that the view is bound to changes.

My view has an observer on the controller model, like so:

App.SomeView = Em.View.extend
  modelDidChange: (()->
    # do stuff
  ).observes('controller.model')

When the model changes, modelDidChange is called twice.

Why is that?

Is there a better/different way to achieve what I'm trying to do here?

Using Ember 1.3.0.

3
Did you find a solution to your problem. I am having the same issue. Any help is appreciated - Ben

3 Answers

0
votes

Are you sure that your view needs to know when the model changes? The view's template gets its properties from the controller, and should update automatically when they change. You certainly want to avoid any observers if you can.

But I don't know much about your use case, so assuming that it's necessary, I would try a debouncer. It's likely that the model isn't changed twice, the event is just fired twice. Ember has a LOT of action that happens in between user hooks, so the model is probably just set to the same value twice. Use a debouncer to have your method called just once.

0
votes
Ember.beginPropertyChanges();
  # model updates
Ember.endPropertyChanges();
0
votes

The first time it fires because you made a change in your browser and that change gets sent to the Ember data store which triggers the observer callback. The store then makes an update request to the backend which responds with an updated model, when the store receives this updated model it triggers the observer callback once again.