5

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.

stubotnik
  • 1,952
  • 2
  • 17
  • 31
  • Did you find a solution to your problem. I am having the same issue. Any help is appreciated – Ben Apr 08 '14 at 12:27

3 Answers3

0

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.

Community
  • 1
  • 1
GJK
  • 37,023
  • 8
  • 55
  • 74
  • Yeah, it's on odd use case. I need to unload/load a swf (don't ask) on model change. Checking out debouncing now... – stubotnik Jan 22 '14 at 13:33
  • The documentation for the `didInsertElement` event says that it fires after the view is re-rendered. It's possible that the view is re-rendered every time the model changes. If so, that would be the ideal scenario for you (along with the `willDestoryElement` event). Maybe try running a quick test to see if changing the model re-renders the view. – GJK Jan 22 '14 at 13:39
  • unfortunately, no. didInsertElement only fires once. my view is permanently visible in the app, so I guess the re-rendering doesn't apply here – stubotnik Jan 22 '14 at 13:47
  • I guess it fires twice because at some point model is null ? and then the new model is set ?, I don't know how that process is done. So, what I can recommend is to add a Ember.run.once(this, function() {}) in the observer, so that the observer only fires once in the current Ember Loop. – fanta Jan 22 '14 at 16:00
  • Ember.run.once and Ember.run.debounce both fire twice. Seems to imply the 2 events are part of separate Ember run loops – stubotnik Jan 28 '14 at 11:12
0
Ember.beginPropertyChanges();
  # model updates
Ember.endPropertyChanges();
Ben
  • 2,560
  • 4
  • 29
  • 43
0

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.

alalani
  • 507
  • 4
  • 13