Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember Model Object hasMany does not return array as I would expect

I am trying to use Ember Data's hasMany field to return me an array and get the count of the items in the array as a computed property. However, when I do the following, it returns me an object (which appears to a promise because of the {async: true}?) instead of the array I expected.

App.Shift = DS.Model.extend({
  name: DS.attr('string'),
  people: DS.hasMany('person', {async: true});
  number_of_people: (function(){
    this.get('people').length
  }).property('people')
)};

App.Person = DS.Model.extend({
  first_name: DS.attr('string'),
  last_name: DS.attr('string')
});

Update: I would like to return the length of people. I tried this but when I access the property I get the promise object returned still instead of the value of completed promise in the then. How would I get the value of the evaluated promised to be returned?

number_of_people: (function(){
  return this.get('people').then(function(people){
    return people.get('length');
  });
})
like image 500
williamsbdev Avatar asked Oct 02 '22 00:10

williamsbdev


1 Answers

It's a promise array, meaning the first time you try to access it it will begin fetching the data, and when it's done you can access it from that promise array. Additionally it's a promise, so you can use then(...) on it to access the values in an async way.

shift.get('people').then(function(people){
  console.log(people.get('length'));
});

It's important to remember that it's async, so depending on where you're using the value it will change from 0 to 0+ at some point. The corrected computed property below will update anytime the length updates

 number_of_people: function(){
   return this.get('people.length');
 }.property('people.length')

in the template

{{number_of_people}}

That being said, this computed property is kind of pointless, you could just use it in the template like so and it would update as well

{{people.length}}
like image 76
Kingpin2k Avatar answered Oct 13 '22 10:10

Kingpin2k