Shakeeb Ahmed
Shakeeb Ahmed

Reputation: 111

Ember-Data: Knowing when a RecordArray is completely populated

I have a situation where isLoaded on a DS.RecordArray changes to true but the content, length property of the RecordArray is still empty, 0 at that time and only changes later.

Sample Code(coffeescript):

@set('followRequests', App.FollowRequests.find())

...

whenDataLoads: (->

console.log @get('followRequests.isLoaded')
console.log @get('followRequests.length')
@set('content', @get('followRequests').toArray() )

).observes('followRequests.isLoaded')

The first log statement is true while the second is 0 and the template which uses this data is empty. When I see the actual AJAX request I see that the request does return an array of records. And the length and content of the RecordArray do change some time later as seen in the Browser console by doing:

App.Router.myController.get('followRequests').get('length') ---> 12

However this code(below) does populate the content in the template, but it runs 12 times...

whenDataLoads: (->
console.log @get('followRequests.isLoaded')
console.log @get('followRequests.length')

@set('content', @get('followRequests').toArray() )

).observes('followRequests.length')

What's the right way to know when the RecordArray is completely populated...??

Upvotes: 5

Views: 2223

Answers (2)

rxgx
rxgx

Reputation: 5160

In Ember Data beta 1.0.0, you'll request the record(s) using the provided store property in a route or controller.

// fetch one
var promiseArray = this.store.find('follow_request', follow_request_id);

// fetch all
var promiseArray = this.store.find('follow_request');

// set callbacks on promise array
promiseArray.then(onFollowRequestSuccess, onFollowRequestFailure);

// or set callbacks on promise object
var promise = promiseArray.get('promise');
promise.then(onFollowRequestSuccess, onFollowRequestFailure);

// or use computed property
App.FollowRequestsController = Ember.ArrayController.extend({
    loadedCount: function() {
        return this.get('content.@each').filterBy('isLoaded', true).length;
    }.property('[email protected]').cacheable()
});

Upvotes: 0

Myslik
Myslik

Reputation: 1178

Since the time Ember.js uses promises you can do this

App.FollowRequests.find().then(function () {
    // This callback will fire when array is loaded
});

Upvotes: 2

Related Questions