将自定义属性添加到集合的每个项目

时间:2014-07-24 14:27:46

标签: backbone.js handlebars.js

我正在尝试将自定义属性添加到集合的每个项目中,但它不会显示在模板中。

我有很多引号都有client_id。现在我想通过client_id获取客户端并将其添加到集合条目中。通常,它在使用console.log检查填充对象时有效,但它不会显示在模板中。

这就是我尝试的方式:

sprocket.QuotationsView = Backbone.View.extend({
    id: 'content-inner',

    initialize: function(options) {
      // instantiate Collection
      this.collection = new Quotations();

      // compile Handlebars template
      this.tpl = Handlebars.compile(this.template);
    },

    render: function() {
      var self = this;
      var obj = this.el;

      // get quotations and set data to handlebars template
      $.when(this.collection.fetch()).then(function(quotations) {

        $.each(quotations, function(i, quotation) {

          var loadContact = new Contact({id: quotation.contact_id}).fetch();
          $.when(loadContact).then(function(contact) {
            quotations[i]['contact'] = contact;
          });

        });

        $(obj).html(self.tpl(quotations));

      // if response is empty (no quotations in database), set empty template
      }, function() {
        $(obj).html(self.tpl);
      });

      return this;
    }
});

我的模板如下所示:

<div>
  {{#if .}}
    {{#each .}}
      {{number}} <!-- this works -->
      {{contact}} <!-- this doesn't work -->
      {{contact.name}} <!-- this doesn't work too -->
    {{/each}}
  {{/if}}
</div>

1 个答案:

答案 0 :(得分:3)

这是因为实际更改Quotation.attribute.contact(即你的quotations[i]['contact'] = contact;行)内部数据的回调正在获取Contact之后正好在模板之后执行被渲染。

$.each(quotations, function(i, quotation) {

  var loadContact = new Contact({id: quotation.contact_id}).fetch();
  // This is the callback that is being executed after the backend responds
  $.when(loadContact).then(function(contact) {
     quotations[i]['contact'] = contact;
  });

});

// This is the template rendering which is before the server has time to respond
$(obj).html(self.tpl(quotations));

在提取所有Contacts并将其添加到Quotations后,代替模板。

解决此问题的快捷方法:

  1. 创建一个循环,在所有包含回调的函数内加载Contacts
  2. 在所有Contacts加载后调用回调。
  3. 回调应该呈现模板。
  4. 这是一个个人观点,绝不是这个问题的答案:我不喜欢后端的数据逻辑以及同一类中的视图渲染和逻辑。我使用Backbone.MarionetteViewController拆分为两个由事件松散耦合的不同实体。只有Controller知道View且只有View知道DOM