【问题标题】:Ember.js - can't get or set model propertyEmber.js - 无法获取或设置模型属性
【发布时间】:2015-02-06 01:08:29
【问题描述】:

我有一个带有如下装置的 Ember.js 模型:

App.Category = DS.Model.extend({
    category: attr('string'),
    friendly: attr('string'),
    iconUrl: attr('string'),
    isPrimary: attr('bool'),
    isSecondary: attr('bool'),
    isTertiaryOne: attr('bool'),
    isTertiaryTwo: attr('bool')
});

App.Category.reopenClass({
    FIXTURES: [
        {
            id: 1,
            category: 'recommended',
            friendly: 'recommended for you',
            iconUrl: 'image1.png',
            isPrimary: true,
            isSecondary: false,
            isTertiaryOne: false,
            isTertiaryTwo: false
        },
        {
            id: 2,
            category: 'recent',
            friendly: 'recently viewed',
            iconUrl: 'image2.png',
            isPrimary: false,
            isSecondary: true,
            isTertiaryOne: false,
            isTertiaryTwo: false
        }
    ]
});

我要做的就是从特定模型中检索一个属性值,并在我的控制器中的操作中将其设置为一个新值:

App.CategoryController = Ember.ArrayController.extend({    
    actions: {
        tileClick: function (selectedCategory) {
            var cat = this.store.find('category', { category: selectedCategory });
            console.log(cat.get('isPrimary'));
            cat.set('isPrimary', true);
        }
    }
});

Emberjs 网站指南说,我需要做的就是设置一个值:

var tyrion = this.store.find('person', 1);
// ...after the record has loaded
tyrion.set('firstName', "Yollo");

但它只是不起作用。

变量 'cat' 存在,如果我在控制台中深入到对象中,我可以看到我想要的属性,所以我知道选择了正确的模型。

【问题讨论】:

    标签: ember.js


    【解决方案1】:

    store.find 方法返回一个承诺,所以你必须(如你所写)等到它被加载。

    您应该阅读更多关于 Promise 的内容,但您现在可以做的是:

    var cat = this.store.find('category', {
      category: selectedCategory
    }).then(function(categories) {
      categories.forEach(function(category) {
        category.set('isPrimary', true);
      });
    });
    

    请注意,如果您使用查询参数(find 与对象实际上是 findQuery),您将获得模型列表,而不是特定模型,即使只找到一个。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      相关资源
      最近更新 更多