ohcibi
ohcibi

Reputation: 2698

How to acess the length of a find() result in Ember.js

THE ANSWER TO THIS QUESTION AND THIS WHOLE QUESTION IS OBSOLETE. EMBER DATA HAS CHANGED A LOT. READ THIS: http://guides.emberjs.com/v1.11.0/models/

I have this little Ember application:

window.App = Ember.Application.create();

App.Store = DS.Store.extend({
  revision: 11,
  adapter: DS.FixtureAdapter({
    simulateRemoteResponse: false
  })
});

App.Model = DS.Model.extend({
  title: DS.attr('string')
});
App.Model.FIXTURES = [];

App.ready = function() {
  console.dir(App.Model.find().get('length'));
  App.Model.createRecord({id: 1, title: "TEST"});
  console.dir(App.Model.find().get('length'));
  console.dir(App.Model.find(1).get('title'));
};

I get the right title in console.dir(App.Model.find(1).get('title') however both of the get('length') calls return 0. What am I missing?

Here is a (non-) working jsbin: http://jsbin.com/uxalap/6/edit

Upvotes: 8

Views: 4916

Answers (1)

Mudassir Ali
Mudassir Ali

Reputation: 8041

The reason might be that you are invoking get("length") even before the data has been loaded,

Basically when you do App.Model.find() it returns you an instance of RecordArray but it wont have data, in the background it queries with the database and will fetch the data, now once the data is loaded you'll find the actual length

you might try adding an Observer on isLoaded property as follows

record = App.store.findQuery(App.Model);
alertCount = function(){
  if(record.isLoaded){
    alert(record.get("length"));
  }
};
Ember.addObserver("isLoaded", record, alertCount);

Upvotes: 9

Related Questions