[英]Re-render a template after a model is added to a collection
我有與模型關聯的消息列表:
App.User = DS.Model.extend({
displayName: DS.attr('string'),
email: DS.attr('string'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
location: DS.attr('string'),
messages: DS.hasMany('message', { async: true })
});
App.Message = DS.Model.extend({
user: DS.belongsTo('user'),
recipient: DS.belongsTo('user'),
createdAt: DS.attr('isodate'),
updatedAt: DS.attr('isodate'),
fullText: DS.attr('string'),
subject: DS.attr('string')
});
我這樣渲染用戶的消息:
<script type="text/x-handlebars" data-template-name="profile">
<form class="new-message navbar-form" role="search" {{action "sendMessage" on="submit"}}>
{{textarea valueBinding="newMessageText" rows="3" placeholder="Send a Message"}}
<button type="submit" class="btn btn-default btn-lg btn-block" style="margin-top: 10px">Submit</button>
</form>
{{#each message in messages}}
<div class="message text-left">
<div class="page-header clearfix">
<p class="created-at">{{format-date message.createdAt}}</p>
<img class="profile-pic" src="http://lorempixel.com/24/24/people" alt="profile" class="img-rounded">
<p class="subject">{{message.subject}}</p>
</div>
<p class="full-text">{{message.fullText}}</p>
</div>
{{/each}}
</script>
使用上面的表單提交新消息時,新消息將添加到存儲中並保存到服務器。 問題是執行save
時,郵件列表不會重新呈現為包括新添加的郵件:
App.UserController = Ember.ObjectController.extend({
newMessageText: '',
actions: {
sendMessage: function() {
var that = this;
var message = this.get('store').createRecord('message', {
fullText: this.newMessageText,
recipient: this.get('model')
});
message.save().then(function () {
// A new message is added to the store linked to the user, but the
// newly-saved message is not added to the template.
that.set('newMessageText', '');
});
}
}
});
確保添加到商店的新消息迫使我的模板重新呈現的正確方法是什么?
您需要對消息列表使用ArrayController或Ember.Array (取決於您的需求)。 之所以需要其中之一,是因為您希望對象是可觀察的,以便模板使用的自動更新機制可以對更改做出反應。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.