Javascript 如何在控制器对添加项执行操作后更新视图
我想在添加后自动更新评论列表 问题是,我从带有fixture的emberjs示例开始,并对其进行了修改,以便可以在页面的开头获取当前数据。我还通过ajax添加了评论功能,所有这些功能都运行良好。现在我只是不知道如何使新的评论在添加后自动出现 这是我的应用程序代码:Javascript 如何在控制器对添加项执行操作后更新视图,javascript,ajax,ember.js,Javascript,Ajax,Ember.js,我想在添加后自动更新评论列表 问题是,我从带有fixture的emberjs示例开始,并对其进行了修改,以便可以在页面的开头获取当前数据。我还通过ajax添加了评论功能,所有这些功能都运行良好。现在我只是不知道如何使新的评论在添加后自动出现 这是我的应用程序代码: window.Comments = Ember.Application.create(); Comments.Comment = DS.Model.extend({ content: DS.attr('string') });
window.Comments = Ember.Application.create();
Comments.Comment = DS.Model.extend({
content: DS.attr('string')
});
Comments.ApplicationController = Ember.ArrayController.extend({
rootElement: "#out",
actions: {
createComment: function () {
var title = $('#new-comment').val();
if (!title.trim()) { return; }
var comment = this.store.createRecord('comment', {
content: title
});
this.set('newContent', '');
comment.save();
}
}
});
Comments.commentsView = Ember.View.extend({
id: 'com',
layoutName: 'commentsTemplate',
comments: null,
init: function() {
console.log('init');
var par = this;
$.ajax({
url: "/getcomments",
type: "GET",
success: function(data) {
par.set("comments", data);
}
});
}
});
这是我的模板
<div id="out"></div>
<script type="text/x-handlebars">
<div class="container">
<div class="row">
<div class="col-xs-6">
{{#view Comments.commentsView}}{{/view}}
</div>
</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="commentsTemplate">
{{#each comment in view.comments}}
<div class="well">
<b>{{comment.content}}</b>
</div>
{{/each}}
<br />
{{input type="text" id="new-comment" placeholder="What you want to say?" value=newContent action="createComment"}}
</script>
{{{#查看评论.评论视图}{{/view}
{{{#视图中的每个注释。注释}
{{comment.content}
{{/每个}}
{{input type=“text”id=“new comment”placeholder=“您想说什么?”value=newContent action=“createComment”}
顺便说一句,我有
var title=$(“#新注释”).val()
causethis.get('newContent')
返回了未定义的值,因此我必须做一些事情使其正常工作您正在使用store创建和保存新注释,但是在视图初始化期间使用原始json请求从服务器获取视图的属性
显然,您还需要使用存储来检索注释。在这种情况下,您的集合将自动更新视图
按照惯例,它应该在控制器中:
Comments.ApplicationController = Ember.ArrayController.extend({
rootElement: "#out",
content: null,
loadComments: function() {
this.set('content', this.store.find('comment'))
},
init: function() { this.loadComments(); this._super() }
顺便说一句,在保存之前还会添加注释:我不太喜欢的功能。为了避免这种情况,我们可能会过滤注释(不确定确切的语法):
当您将ember与数据存储连接起来时,在创建新记录时会自动更新列表@你什么意思?我以为我已经这么做了:/就像@Ivan说的,使用商店!
persisted: function () {
this.get('content').filterBy('isNew', false)
}.property('content') // or .observes('content.@each') i'm not sure