0

I have a Phone model. I want to cache all phones on my application:

cachePhones : function () {
    this.set('phones', this.Phone.find());
},

And get the countries for which I have available phones:

getCountries : function () {
    var phones = this.get('phones.content');
    var countries = new this.dataSet(), country;
    console.log('phones=%o', phones.length);
    for (var index = 0, length = phones.length; index < length; index++) {
        country = phones[index].record.get('country');
        console.log('Adding %o', country);
        countries.add(country, true);
    }
    console.log('countries=%o', countries.keys());
    return countries.keys();
},

(dataSet is just a set implementation in javascript)

I am not sure this is the right way to walk the ArrayController:

  • do I really need to access the content?
  • do I really need to access record?

This feels like hacking around my way in the ember internals. I have tried before this:

var phones = this.get('phones');
var countries = new this.dataSet(), country;
for (var index = 0, length = phones.length; index < length; index++) {
    country = phones[index].country;
    countries.add(country, true);
}

But it was not working at all. What is the canonical way of walking an ArrayController?

Community
  • 1
  • 1
blueFast
  • 41,341
  • 63
  • 198
  • 344

2 Answers2

2

Have you tried something like this? Normally you should always be fine with using the functional methods Ember offers for its collections.

var phones = this.get('phones');
var countries = new this.dataSet(), country;
phones.forEach(function(phone, index){
  country = phone.get("country");
  countries.add(country, true);
});
mavilein
  • 11,648
  • 4
  • 43
  • 48
2

Besides @mavilein correct answer one thing worth mentioning is that if you have a model like App.Phone then after you do App.Phone.find() and the records are fetched, your Store has already a cache which you can consult with App.Phone.all() this will not make another request but gives you the records available in the Store.

Hope it helps.

intuitivepixel
  • 23,302
  • 3
  • 57
  • 51
  • What if I do not know if the phones have already been requested? Can I access `App.Phone.all()`, and a `App.Phone.find()` will be done automatically? – blueFast Aug 06 '13 at 15:22
  • no, `.all()` only retrieves the already fetched records if any, see here: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/system/store.js#L848 – intuitivepixel Aug 06 '13 at 16:12