Theozaurus
Theozaurus

Reputation: 963

Loading data asynchronously in ember-data

I'm writing an application based on ember-data, it loads up all of its data asynchronously. However, the didLoad function does not get called until find is used. For example:

App = Ember.Application.create();
App.Store = DS.Store.create({revision: 3});
App.Thing = DS.Model.extend({
  didLoad: function(){
    alert("I loaded " + this.get('id'));
  }
});
App.Store.load(App.Thing,{id: "foo"});

...will not trigger the alert, and findAll will not return the model. However, when I run:

App.Store.find(App.Thing,"foo");

The didLoad function will trigger, and it can be found with App.Store.findAll(App.Thing).

What's going on?

Upvotes: 1

Views: 2122

Answers (1)

DominikGuzei
DominikGuzei

Reputation: 599

The ember-data source code explains it well:

// A record enters this state when the store askes
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.

loading: DS.State.create({
  // TRANSITIONS
  exit: function(manager) {
    var record = get(manager, 'record');
    record.fire('didLoad');
  },

  // EVENTS
  didChangeData: function(manager, data) {
    didChangeData(manager);
    manager.send('loadedData');
  },

  loadedData: function(manager) {
    manager.goToState('loaded');
  }
}),

this means that 'didLoad' will only be triggered when the record was loaded via the adapter.

The 'find' method asks the adapter for the data - this looks it up in the pool of currently available data hashes and in your case finds it, because you already provided it. In other cases however the data maybe does not exist locally in the browser but remain on the server, which would trigger an ajax request in the adapter to fetch it.

So 'didLoad' currently only works in combination with an adapter (e.g: find)

But I totally agree with you that this should be changed since triggering 'didLoad' on models that are loaded vai Store.load seems pretty obvious ;-)

Upvotes: 1

Related Questions