簡體   English   中英

在模板上渲染骨干集合時無法獲取模型的cid

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

我試圖在使用mustache.js構建的模板上呈現主干集合。 問題是我無法在模板中獲得模型的cid。 我的代碼是

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

從上面的代碼中,我可以得到aptId,beginTime和end Time,但不是Cid。 如何在模板上渲染模型時從集合中獲取模型的Cid?

我從視圖中看到的渲染方法如下所示

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

使用cid作為模型的唯一標識符也有任何缺點嗎?

提前致謝 !!!

默認情況下, toJSON輸出中不包含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})

順便說一下,如果您不需要擴展所有模型的行為,您可以使用parse方法將cid添加到模型中。 例如,您有集合'Collection'。 您可以為此集合指定模型,並覆蓋parse方法以將模型的cid附加到響應。

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

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

因此,您將能夠從模型的屬性中獲取cid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM