out*_*344 7 ember.js ember-data
我在我的应用程序中使用了一个ArrayController,它通过应用程序的路由器从Ember Data REST调用中提供:
postsController.connectOutlet('comment', App.Comment.find({post_id: post_id}));
Run Code Online (Sandbox Code Playgroud)
对于Post UI,我可以添加/删除评论.当我这样做时,我希望能够通过删除或添加相同的元素来更新postsController的contentArray,以便为用户提供可视反馈,但是Ember Data并不好玩:
Uncaught Error: The result of a server query (on App.Comment) is immutable.
Run Code Online (Sandbox Code Playgroud)
每低于sly7_7的评论,我只注意到这个结果确实DS.RecordArray时没有查询(App.Comment.find()),但在那里有一个查询(App.Comment.find({POST_ID的情况: post_id}),返回DS.AdapterPopulatedRecordArray.
我是否必须.observes('contentArray')并创建一个可变副本?或者有更好的方法吗?
以下是我最终实现的解决方案.正如问题中所提出的,我所知道的唯一解决方案是创建我通过添加和删除维护的内容的可变副本:
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
然后在模板中,绑定到此计算属性:
{{#each comment in currentComments}}
...
{{/each}}
Run Code Online (Sandbox Code Playgroud)
我对这个解决方案不满意 - 如果有更好的方法,我很乐意听到它.