简体   繁体   English

在模板上渲染骨干集合时无法获取模型的cid

[英]cannot get the cid of the model while rendering a backbone collection over a template

I am trying to render a backbone collection on a template that is built with mustache.js . 我试图在使用mustache.js构建的模板上呈现主干集合。 The problem is I couldn't get the cid of the model in the template. 问题是我无法在模板中获得模型的cid。 My code is 我的代码是

        <div class="phone span4">
            <h5> Phone Appointments</h5>
            {{ _.each(slots, function(slot) { }}
                {{ if(slot.aptType == "P"){ }}
                    <h6 cid="{{=slot.cid}}"  aptId="{{=slot.aptId}}"> {{=slot.beginTime}}  - {{=slot.endTime}} </h6>
                {{  }   }}
            {{  }); }}
        </div>

from the above code, I can get the aptId, beginTime and end Time, but not the Cid. 从上面的代码中,我可以得到aptId,beginTime和end Time,但不是Cid。 How to get the Cid of the model from a collection while rendering it on a template? 如何在模板上渲染模型时从集合中获取模型的Cid?

and my render method from the view looks like this 我从视图中看到的渲染方法如下所示

    render:function(){
    var template = _.template($("#slot-display-template").html());
    compiledTmp = template({slots: this.collection.toJSON()})
    this.$el.append(compiledTmp);
    }

Also is there any disadvantage of using cid as the unique identifier of a model ? 使用cid作为模型的唯一标识符也有任何缺点吗?

Thanks in advance !!! 提前致谢 !!!

The cid is not included by default in the toJSON output. 默认情况下, toJSON输出中不包含cid You will need to override toJSON in your model definition and include cid . 您需要在模型定义中覆盖toJSON并包含cid

toJSON: function() {
  var json = Backbone.Model.prototype.toJSON.apply(this, arguments);
  json.cid = this.cid;
  return json;
}

如果您需要广告解决方案,这也可以:

var params = _.extend({}, this.model.toJSON(), {cid: this.model.cid})

By the way if you don't need to extend behavior of all models you can just add cid to your model using parse method. 顺便说一下,如果您不需要扩展所有模型的行为,您可以使用parse方法将cid添加到模型中。 For example you have collection 'Collection'. 例如,您有集合'Collection'。 You can specify model for this collection and override parse method to attach model's cid to the response. 您可以为此集合指定模型,并覆盖parse方法以将模型的cid附加到响应。

var Collection = Backbone.Collection.extend({
    model: Model
});

var Model = Backbone.Model.extend({
    parse: function(response) {
        response.cid = this.cid;
        return response;
    }
});

So you'll be able to get cid from model's attributes. 因此,您将能够从模型的属性中获取cid

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

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