如何在具有ember数据的兄弟记录之间放置子记录(beta 17或更高版本)



我的代码在早期版本的ember数据(测试版3和ember 1.5)中运行,但在1.0.0测试版15和ember 1.10.0版本的embe数据中它正在崩溃。我有一个模型,它本身就有父/子关系。

    App.Question = DS.Model.extend({
        name: DS.attr('string'),
        childQuestions: DS.hasMany('question', {async: true, inverse: 'parentQuestion'}),
        parentQuestion: DS.belongsTo('question', {inverse: 'childQuestions'})
    });

现在,我想在我想要的任何位置添加父问题中的子问题。我以前可以在任何位置添加/删除问题,但现在我无法这样做。这是我添加模型的核心逻辑:

addChild: function (parent, afterChild) {
    var position = parent.get('childQuestions').indexOf(afterChild),
            store = this.get('store'),
            jqXHR = Ember.$.ajax({
                url: '/questions',
                dataType: 'json',
                type: 'POST',
                data: {
                    parentQuestion: parent.get('id')
                }
            });

    jqXHR.done(function (data) {
        Ember.run(function () {
            // In later versions of Ember Data, this method returns the actual record
            // that was created so we don't have to hunt for it again with `store.find()`.
            store.pushPayload('question', data);
            store.find('question', data.question.id).then(function (question) {
                parent.get('childQuestions').insertAt(position + 1, question);
            });
        });
    });
}

因此,现在这是突破,并为我创造了这两个问题:

1) 无法将新添加的问题移动到所需位置

2)如果我添加了一些新问题,然后删除了其中的一些问题,然后又添加了另一个新问题,那么它会将所有删除的问题都带回来。我在商店里登记了,但这些记录已经不在商店里了

下面是一个jsbin来演示我遇到的问题:http://emberjs.jsbin.com/geqowibume/1/

我假设我使用的是旧版本的ember数据和ember,我一定是用错误的(非ember)方式做的,你对如何正确解决这些问题的见解将不胜感激。谢谢

更新:发现在上引发的错误https://github.com/emberjs/data/issues/2666

Ember数据1.0.0测试版12似乎解决了问题2,但1仍然是一个问题!

好的,我确实找到了解决这两个问题的解决方案:

addChild: function(parent, afterChild) {
    var position = parent.get('childQuestions').indexOf(afterChild),
        store = this.get('store'),
        jqXHR = Ember.$.ajax({
            url: '/questions',
            dataType: 'json',
            type: 'POST',
            data: {
                parentQuestion: parent.get('id')
            }
        });
    jqXHR.done(function(data) {
        Ember.run(function() {
            store.pushPayload('question', data);
            store.find('question', data.question.id).then(function(question) {
                var childQuestionsArray = parent.get('childQuestions').toArray();
                childQuestionsArray.filterBy('isDeleted', false);
                childQuestionsArray.insertAt(position + 1, question);
                parent.get('childQuestions').clear();
                parent.get('childQuestions').pushObjects(childQuestionsArray);
            });
        });
    });
}

更新:本以为它有效,但现在不行了,在新添加的记录下添加子记录会导致子记录显示在底部!!http://jsbin.com/limagufiwa/edit?html,js,输出

最新更新