简体   繁体   English

将模型添加到集合后,重新渲染模板

[英]Re-render a template after a model is added to a collection

I have a list of messages that are associated with a model: 我有与模型关联的消息列表:

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')

});

I render a user's messages like so: 我这样渲染用户的消息:

<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>

When a new message is submitted using the form above, a new messages is added to the store and saved to the server. 使用上面的表单提交新消息时,新消息将添加到存储中并保存到服务器。 The problem is that the list of messages is not re-rendered to include the newly-added message when the save is performed: 问题是执行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', '');
      });
    }

  }

});

What's the proper way to ensure new messages added to the store force my template to re-render? 确保添加到商店的新消息迫使我的模板重新呈现的正确方法是什么?

You need to use an ArrayController for the messages list, or an Ember.Array (depends on your needs). 您需要对消息列表使用ArrayControllerEmber.Array (取决于您的需求)。 You need either of those because you want your object to be observable so that the auto-updating mechanism, that the templates use, can react to the changes. 之所以需要其中之一,是因为您希望对象是可观察的,以便模板使用的自动更新机制可以对更改做出反应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM