我的Ember应用程序中有这条路线:
model: function(params, transition) {
var self = this;
return Ember.RSVP.hash({
photo: self.store.find('photo', params.id),
comments: self.store.query('comment', {id: params.id})
});
},
actions: {
newComment: function(comment) {
var record = this.store.createRecord('comment', comment);
}
}
模板:
{{#each model.comments as |comment|}}
<div class="card">
<div data-userId="{{comment.userId}}">
<b>{{comment.username}}</b>
</div>
<div>
{{comment.content}}
</div>
<span class="hide-on-small-only">{{i18n 'createdAt_lbl'}}: </span>{{format comment.createdAt type='date'}}
</div>
{{/each}}
{{post-comment newComment='newComment' comments=model.comments}}
和评论模型:
export default DS.Model.extend({
commentHash: DS.attr('string'),
content: DS.attr('string'),
createdAt: DS.attr('date'),
username: DS.attr('string'),
userHash: DS.attr('string'),
userId: DS.attr('number'),
});
评论后组件是负责调用newComment操作的组件:
// post-comment component
var self = this;
// get the new comment content from textarea
var $contentArea = this.$('#postCommentContent');
var content = $contentArea.val();
var newComment = {
userId: localStorage.getItem('userId'),
content: content,
createdAt: moment().format('MMMM Do YYYY, h:mm:ss a')
};
self.sendAction('newComment', newComment);
我需要的是能够以新的方式添加新的本地评论(不会在服务器上保留它)并使模板更新以显示新添加的记录而无需完整的页面刷新
答案 0 :(得分:1)
制作评论列表的可修改副本并将其保留在控制器上:
setupController(controller, model) {
this._super(...arguments);
controller.set('comments', model.comments.toArray());
}
您需要制作副本的原因是store.query
的返回值由于各种原因而不可写。可能还有其他方法可以制作副本,但toArray
似乎运作良好。
创建后,将新评论添加到此列表中:
actions: {
newComment: function(comment) {
var record = this.store.createRecord('comment', comment);
this.get('comments').pushObject(record);
}
}
在模板中,遍历控制器属性:
{#each comments as |comment|}}
答案 1 :(得分:0)
它应该像这样工作:
newComment: function(comment) {
var record = this.store.createRecord('comment', comment);
var commentsModel = this.get('model.comments'); // or this.get('comments'), depending where you action resides
commentsModel.pushObject(record);
this.set('model.comments', commentsModel); // or this.set('comments'), depending where you action resides
}
仅当您确实有评论时才有效。如果没有,您首先需要将注释初始化为空数组。否则:
newComment: function(comment) {
var record = this.store.createRecord('comment', comment);
var commentsModel = this.get('model.comments'); // or this.get('comments'), depending where you action resides
if(!commentsModel){
commentsModel = Ember.A();
}
commentsModel.pushObject(record);
this.set('model.comments', commentsModel); // or this.set('comments'), depending where you action resides
}
}