从 Ember Data 支持的 ArrayController 添加/删除项目 [英] add/delete items from Ember Data backed ArrayController
问题描述
我在我的应用程序中使用了一个 ArrayController,它通过应用程序的路由器从 Ember Data REST 调用提供:
I'm using an ArrayController in my application that is fed from a Ember Data REST call via the application's Router:
postsController.connectOutlet('comment', App.Comment.find({post_id: post_id}));
对于帖子 UI,我可以添加/删除评论.当我这样做时,我希望能够通过删除或添加相同的元素来更新 postsController 的 contentArray 以提供用户视觉反馈,但 Ember Data 并不好玩:
For the Post UI, I have the ability to add/remove Comments. When I do this, I'd like to be able to update the contentArray of the postsController by deleting or adding the same element to give the user visual feedback, but Ember Data is no fun:
Uncaught Error: The result of a server query (on App.Comment) is immutable.
根据下面sly7_7的评论,我只是注意到当没有查询(App.Comment.find())时,结果确实是DS.RecordArray,但在有查询的情况下(App.Comment.find({post_id: post_id}),返回一个 DS.AdapterPopulatedRecordArray.
Per sly7_7's comment below, I just noticed that the result is indeed DS.RecordArray when there is no query (App.Comment.find()), but in the case where there is a query (App.Comment.find({post_id: post_id}), a DS.AdapterPopulatedRecordArray is returned.
我是否必须 .observes('contentArray') 并创建一个可变副本?或者有更好的方法吗?
Do I have to .observes('contentArray') and create a mutable copy? Or is there a better way of doing this?
推荐答案
这是我最终为解决这个问题而实施的.正如问题中所提出的,我所知道的唯一解决方案是创建我通过添加和删除维护的内容的可变副本:
Here is what I ended up implementing to solve this. As proposed in the question, the only solution I know about is to create a mutable copy of the content that I maintain through add and deletes:
contentChanged: function() {
var mutableComments = [];
this.get('content').forEach(function(comment) {
mutableComments.pushObject(comment);
});
this.set('currentComments', mutableComments);
}.observes('content', 'content.isLoaded'),
addComment: function(comment) {
var i;
var currentComments = this.get('currentComments');
for (i = 0; i < this.get('currentComments.length'); i++) {
if (currentComments[i].get('date') < comment.get('date')) {
this.get('currentComments').insertAt(i, comment);
return;
}
}
// fell through --> add it to the end.
this.get('currentComments').pushObject(comment);
},
removeComment: function(comment) {
this.get('currentComments').forEach(function(item, i, currentComments) {
if (item.get('id') == comment.get('id')) {
currentComments.removeAt(i, 1);
}
});
}
然后在模板中,绑定到这个计算属性:
Then in the template, bind to the this computed property:
{{#each comment in currentComments}}
...
{{/each}}
我对这个解决方案不满意 - 如果有更好的方法,我很想知道.
I'm not satisfied with this solution - if there is a better way to do it, I'd love to hear about it.
这篇关于从 Ember Data 支持的 ArrayController 添加/删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!