Ember.js computed property from store

3.8k Views Asked by At

I'm trying to get a simple count of objects returned by REST get request from the server to use in another controller in Ember.js

For this reason I need to make an additional request to the server. Basically here's my code and it almost works.. but not quite yet. Maybe someone can figure out why.

It return a PromiseArray, that's why I'm using .then() to access the properties .

App.TestController = Ember.ObjectController.extend({
    totalCount: function() {
        return this.store.find('question', {test: this.get('id')}).then(function(items) {
            var count = items.get('content').get('length');
            console.log(count); // This actually logs correct values
            return count;
        })
    }.property('question')
})

It does what it suppose to do and I'm getting correct values printed out in the console.log(), but when I try to use {{totalCount}} in the view template I'm getting [object Object] instead of an integer.

Also, am I properly observing the questions property? if the value changes in its proper controller will the value update?

Thanks

2

There are 2 best solutions below

0
On

Alternatively totalCount might lazily set itself, like this:

App.TestController = Ember.ObjectController.extend({
    totalCount: 0,
    question: // evaluate to something,
    totalCount: function() {
        var that = this;
        that.store.find('question', {test: that.get('id')}).then(function(items)     {
            var count = items.get('content').get('length');
            that.set('totalCount', count);
        })
    }.observes('question').property()
})
5
On

The problem you are seeing is because your are returning a promise as the value of the property and handlebars won't evaluate that promise for you. What you need to do is create a separate function that observes question and then call your store there to update the totalCount-property. It would be something like this.

App.TestController = Ember.ObjectController.extend({
    totalCount: 0,
    totalCountUpdate: function() {
        var that = this;
        this.store.find('question', {test: this.get('id')}).then(function(items)     {
            var count = items.get('content').get('length');
            console.log(count);
            that.set('totalCount', count);
        })
    }.observes('question')
})