简体   繁体   English

Ember.js来自商店的计算属性

[英]Ember.js computed property from store

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 我正在尝试从服务器获取REST返回的对象的简单计数,以获取要在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 . 它返回一个PromiseArray,这就是为什么我使用.then()来访问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. 它完成了它应该做的事情,并且我在console.log()中得到了正确的输出值,但是当我尝试在视图模板中使用{{totalCount}} ,我得到的是[object Object]而不是整数。

Also, am I properly observing the questions property? 另外,我是否可以正确观察questions属性? if the value changes in its proper controller will the value update? 如果值在其适当的控制器中更改,则值会更新吗?

Thanks 谢谢

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. 您需要做的是创建一个观察question的单独函数,然后在那儿调用您的商店以更新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')
})

Alternatively totalCount might lazily set itself, like this: 另外, totalCount可能会延迟设置自身,如下所示:

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()
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM