首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将自定义属性添加到集合的每个项

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

Stack Overflow用户
提问于 2014-07-24 14:27:46
回答 1查看 115关注 0票数 0

我正在尝试向集合的每个项添加一个自定义属性,但它没有显示在模板中。

我有很多client_id的报价。现在,我希望通过client_id获取客户机,并将其添加到集合条目中。通常,当使用console.log检查填充对象时,它可以工作,但是它不会出现在模板中。

我就是这么试的:

代码语言:javascript
复制
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;
    }
});

我的模板如下所示:

代码语言:javascript
复制
<div>
  {{#if .}}
    {{#each .}}
      {{number}} <!-- this works -->
      {{contact}} <!-- this doesn't work -->
      {{contact.name}} <!-- this doesn't work too -->
    {{/each}}
  {{/if}}
</div>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-28 21:43:06

这是因为回调实际上改变了Quotation.attribute.contact中的数据(即。您的quotations[i]['contact'] = contact;行)是在获取模板呈现之后的Contact之后执行的。

代码语言:javascript
复制
$.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. 回调应该呈现模板。

这是个人观点,绝不是对这个问题的回答:我不喜欢后端的数据逻辑,也不喜欢同一个类中的视图呈现和逻辑。我使用Backbone.MarionetteViewController拆分到由事件松散耦合的两个不同实体中。只有Controller知道View,只有View知道DOM

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24936468

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档