ember.js - Ember push record in model and update template -
i have route in ember app:
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); } }
the template:
{{#each model.comments |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}}
and comment model:
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'), });
the post-comment component 1 responsible call newcomment action:
// post-comment component var self = this; // new comment content textarea var $contentarea = this.$('#postcommentcontent'); var content = $contentarea.val(); var newcomment = { userid: localstorage.getitem('userid'), content: content, createdat: moment().format('mmmm yyyy, h:mm:ss a') }; self.sendaction('newcomment', newcomment);
what need able add new local comment (without persisting on server) dinamically , make template update show newly added record without complete page refresh
make modifiable copy of list of comments , keep on controller:
setupcontroller(controller, model) { this._super(...arguments); controller.set('comments', model.comments.toarray()); }
the reason need make copy return value store.query
is, various reasons, unwritable. there may other ways make copy toarray
seems work well.
add new comment list after creating it:
actions: { newcomment: function(comment) { var record = this.store.createrecord('comment', comment); this.get('comments').pushobject(record); } }
in template, loop on controller property:
{#each comments |comment|}}
Comments
Post a Comment