Search code examples
ember.jsember-model

Can't get data from a computed property with ember-model


I am making an app with ember.js and ember-model

I have a model named Plugin defined as follows:

Eme.Plugin = Ember.Model.extend
  id: Ember.attr()
  name: Ember.attr()
  description: Ember.attr()
  downloads: Ember.attr()
  tags: Ember.attr()

Eme.Plugin.url = "/api/v1/plugins"
Eme.Plugin.adapter = Ember.RESTAdapter.create()
Eme.Plugin.collectionKey = 'plugins'

I want show the most downloaded in index.hbs ( i use ember-rails)

And i fetch data in IndexRoute 's setupController hook:

Eme.IndexRoute = Em.Route.extend

  setupController: (controller, model)->
    console.log Eme.Plugin.findAll().toArray()
    controller.set 'plugins', Eme.Plugin.findAll()

Output :

[nextObject: function, firstObject: undefined, lastObject: undefined, contains: function, getEach: function…]

But in chrome console i execute Eme.Plugin.findAll().toArray(), i got the results as follows:

[{
  __ember1377710636537: "ember404"
  __ember1377710636537_meta: Meta
  _dirtyAttributes: Array[0]
  _reference: Object
  _super: undefined
  get _data: function() {}
  isLoaded: true
  isNew: false
  set _data: function(value) {}
  __proto__: Object
}, {
  ...
}, {
  ...
}]

In my IndexController have a computed property:

Eme.IndexController = Em.Controller.extend

  mostDownloads:(->
    # console.log @get('plugins').slice(0, 3)
    @get('plugins').slice(0, 3)
  ).property('plugins')

and i iterate the mostDownloads but there is nothing to show, however when i output {{plugins.length}}, i can't get the count of all my data

Who can give a hand to me?


Solution

  • Plugins looks like an array and would need to use the .@each iterator like so:

    Eme.IndexController = Em.Controller.extend({
        // Code
    }).property('plugins.@each')
    

    Here is documentation on @each http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/

    Regarding your array length, I've never had much luck using .length, for length I usually do

    plugins.get('length')
    

    Hope that helps!