Ember.js按名称查找模型项,然后将其添加到现有的不同模型hasMany记录中

Ember.js look up a model item by name, and then add it to an existing different model hasMany record

本文关键字:模型 记录 hasMany 添加 js 查找 Ember 然后      更新时间:2024-03-22

伙计们,我无法理解。我已经挣扎了好几个小时了。我有一个文章模型,可以有多个类别:

// parent
App.Article = DS.Model.extend({
    name: DS.attr('string'),
    category: DS.hasMany('category')
)};
// child
App.Category = DS.Model.extend({
    name: DS.attr('string')
});

通过点击自动完成组件结果,执行以下操作:

  addCategory: function (categoryName) {
        // for the sake of simplicity a default name
        categoryName = 'car';
        // find category instance by name
        this.store.find('category').then(function(category) {
            var categoryItem = category.filterBy('name', categoryName);
            // get categories and add the category to it
            this.get('category').pushObject(categoryItem);
        });
    },

你应该思考的问题是什么。好吧,问题是没有错误,一切似乎都很好。

但是:

  • 当我在Ember Inspector中查看时,我清楚地看到了一个新的文章记录,我看到了已经创建的类别。但hasMany Category记录中没有添加任何类别

所以问题是,如何首先查找Category项,然后将其添加到文章的hasMany记录中?

大编辑:我删除了一些不相关的代码和文本。希望我的问题现在更清楚了。

哇!我可以回答我自己的问题。我对使用.then函数的this感到困惑。

我还清理了我的代码如下:

addCategory: function (categoryName) {
   var self = this;
   // find category model by name
   this.store.find('category').then(function(category) {
       self.get('category').pushObject(category.findBy('name', categoryName));
   });
}

非常感谢您的光临。