Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 847
ohcibi Avatar asked Feb 28 '13 12:02

ohcibi


1 Answers

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);
like image 157
Mudassir Ali Avatar answered Nov 10 '22 20:11

Mudassir Ali