[英]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.