设置属性值的Ember问题

Ember issue with setting attribute value

本文关键字:Ember 问题 属性 设置      更新时间:2023-09-26

我有一个Ember Route类,定义如下;

export default Ember.Route.extend({
    model: function() {
        var compObj = {};
        compObj.gridPara = this.get('gridPara');
        return compObj;
    },
    gridPara: function() {
        var self = this;
        var returnObj = {};
        returnObj.url = '/myService';
        // setting some other returnObj attributes
        var summaryObj = {
            total: {
                label: "Total 1",
                value: "100"
            },
            additional: [{
                label: 'Label 2',
                value: 'val2'
            }, {
                label: 'Label 3',
                value: 'val3'
            }]
        };
        returnObj.summary = summaryObj;
        return returnObj;
    },
    actions: {
        dataLoaded: function(resp) {
            // Here I get the service response and want to set (or overwrite) the summaryObj values
            this.get('gridParams').summary.total.value = resp.numRows;          
        }
    }
});

我的模板看起来像

{{my-grid params=this.gridPara dataLoaded="dataLoaded"}}

现在我想在returnObj上设置"摘要"我已经验证了我在dataLoaded回调中得到了"resp"。

但我在尝试进行时出现以下错误

this.get('gridParams').summary.total.value = resp.numRows;      

未捕获错误:断言失败:必须使用Ember.set()将[对象对象]的value属性设置为100

此外,我如何在summaryObj 中设置/推送"附加"数组

由于错误状态,您必须对值使用set(我假设您在某个地方定义了gridParams?):

this.set('gridParams.summary.total.value', resp.numRows);

为了推送一个新对象,请尝试以下操作:

var additional = this.get('gridParams.additional');
additional.push({label: ..., value: ....});
this.set('gridParams.additional', additional);

不能100%确定,但请尝试一下:

  • 注意物业名称。我想声明"gridPara"并试图获取"gridParams"是一个措辞错误
  • 您应该检索这样的值
    this.get('gridParams.summary.total.value')
  • 你在最后一句中尝试的是一个设置,但就像它是普通的JS一样。在Ember中,你应该这样做this.set('gridParams.summary.total.value',resp.numRows)

只需添加到@Remi答案中,最佳做法是使用

Ember.set('gridParams.summary.total.value', resp.numRows);

回答您评论中的问题假设您想更新索引i处的additional数组。只需执行

var updateItem = additional[i];
Ember.set(updateItem.propertyname,newValue)
//Here propertyname would be the property you want to update and new Value is the new value which you want to set to that property