Reputation: 4641
I want to automatically update comments list after adding
The thing is that I've started from emberjs sample with fixtures and I've modified it so I can get current data on the start of the page. I've added also adding comment feature via ajax and all of this things works well. Now I just don't know how to make new comment automaticly appear after adding it.
This is my app code:
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);
}
});
}
});
and this my template
<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>
btw. I have var title = $('#new-comment').val();
cause this.get('newContent')
was returning undefined value so I had to do something to get it working
Upvotes: 0
Views: 93
Reputation: 1618
You are using store to create and save the new comment, but comments
property of your view taken from server using raw json-request once during the init of view.
Obviously, you need to use store to retrieve comments as well. In this case your collection will update view automatically.
And it should be in the controller by convention:
Comments.ApplicationController = Ember.ArrayController.extend({
rootElement: "#out",
content: null,
loadComments: function() {
this.set('content', this.store.find('comment'))
},
init: function() { this.loadComments(); this._super() }
By the way, comment will be added even before saving: the feature I don't really like. To avoid that, we may filter our comments (not sure about exact syntax):
persisted: function () {
this.get('content').filterBy('isNew', false)
}.property('content') // or .observes('content.@each') i'm not sure
Upvotes: 1