Best way to handle isLoading / isLoaded on ember data model


#1

I have a situation where I am creating a record and submitting it back to the server, the record is returned and then I need to retrieve a hasMany relation from the model through a link on the model that is just returned. The problem is the model isn’t loaded, so the when it goes to retrieve the hasMany, links on _data aren’t populated and the hasMany fails.

Whats the best way to handle isLoaded change? I would use the callback on the model, but that seems like the wrong place to use it since if I need anything else to do something on that callback, that would overwrite any previous methods. I can add observer to the isLoaded flag, but then that is always observing that flag when I only need a once off callback when the model has finished loaded.

It would be nice if when a promise is returned, the model is fully loaded or there was an event to bind to once on the isLoaded method. Anyone have any workarounds or suggestions?

Example of what I’m doing:

mainModel.save()
  .then((returnedModel) ->
     # returnedModel.get("isLoaded") == false
     returnedModel.get("hasManyCollection")
       .then((returnedHasManyCollection") ->
         # collection is empty since when it tried to load the collection the mainModel wasn't loaded
         doFinalCodeHere()
       )
  )

#2

I’m not a big ember-data user, but there is a didLoad event that is triggered.

mainModel.one('didLoad',function() { /* your side-loading logic here */ });


#3

We use observers that automatically remove themselves:

var loadingStateChanged = function (record) {
  if (record.get('isLoaded')) {
    record.removeObserver('isLoaded', loadingStateChanged);
    Ember.run.later(function () {
      _doFinalCodeHere()
    });
  }
};

mainModel.save().then(function (returnedModel) {
  returnedModel.addObserver('isLoaded', loadingStateChanged);
});

Not pretty, but does the job. I just tried to use the didLoad event instead, because I wasn’t aware that it existed before, but that resulted in some strange behavior, so I’m staying with the observers for now :slight_smile: