2

I actually play around with ember js and I'm confused, about the observer behavior.

App.ProjectView = Ember.View.extend({
    modelChanged: function() {
        console.log('modelChanged to: ');
        this.get('controller.model.images').forEach(function(item) {
            console.log(item.get('src'));
        });
    }.observes('controller.model.images')
});

this observer is called two or three times if I access the route. But I did not understand why and can't find any furthur informations.

thanks for any help.

conscience
  • 463
  • 6
  • 21

1 Answers1

3

You can end up with observers firing multiple times as an object is created and populated. In the example above it could be that model.images is created and set to undefined... bam! observer triggered. Then the content of model.images is set to an actual empty array... bam! observer triggered. Then content starts to fill the array... bam! bam! bam! multiple observers could fire.

There are ways to combat this like only doing something with model.images when it is length > 0 or defined. If you know the length of the data being loaded you could only handle the observer when the lengths match. These approaches will vary depending on how your application is structured.

Cory Loken
  • 1,395
  • 8
  • 8
  • ok thanks for the short explanation :) but now I have another strange thing ... if I inspect via chrome console the corresponding object it is a Ember.OrderedSet ... but it does not have the methods of the ordered set which are described in the api docu ... – conscience Mar 27 '13 at 21:55
  • the whole model thing in ember js is pretty weird ... actually I try to create a slideshow with data from a model (the code above is a first approach) ... so another try was a action where I pass the images field ... it works, but only after the action was trigger a second time ... then the model is loaded or something ... how could I handle this async horror with models ? to achieve such a simple goal ? – conscience Mar 27 '13 at 22:10
  • If you are using ember data I'd hook into the didLoad event. That way you aren't receiving messages every time a record is loading onto an array. – Cory Loken Mar 27 '13 at 22:35