Ember.js - 无法获取或设置模型属性

时间:2015-02-06 01:08:30

标签: ember.js

我有一个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'存在,如果我深入钻入控制台中的对象,我可以看到我想要的属性,所以我知道正在选择正确的模型。

1 个答案:

答案 0 :(得分:1)

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

你应该更多地阅读承诺,但你现在可以做的是:

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

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