簡體   English   中英

如何在BackboneJS * marionette * collectionView中打印行線?

[英]how can i print the row line in BackboneJS *marionette* collectionView?

我有一個使用LI itemView創建UL的collectionView。

我想在下划線模板中使用項索引號(count)。 即:

hello (item 0)
world (item 1)

有人知道如何使用牽線木偶計數嗎? 我想避免把它放在模型中。

這就是我希望我的itemView模板看起來像(項目數為n):

<script id="task-template" type="text/html">
          <div class="order"><%=n%></div>
          <div class="title-container">
               <a href="#">...</a>
          </div>
 </script>

任何幫助贊賞,

干杯,

我剛剛找到了一個簡單的方法。 (使用Marionette v1.0.0-rc6)

使用templateHelpers屬性。

在商品視圖中:

MyItemView = Backbone.Marionette.ItemView.extend({
    template: "#my-item-view-template",

    templateHelpers: function(){

        var modelIndex = this.model.collection.indexOf(this.model);
        return {
            index: modelIndex
        }

    }
});

在模板中,您可以使用以下命令打印索引:

<%= index %>

就這樣。

這應該很簡單,因為集合中的模型可以輕松獲取所需的信息。 您需要在模型周圍創建一個“視圖模型”包裝器,以便您可以獲取所需的額外信息。


var createViewModel(model){

  // inherit from the original model
  var vm = Object.create(model);

  // override the original `toJSON` method
  vm.toJSON = function(){
    var json = model.toJSON();

    // add the index
    json.index = model.collection.indexOf(model);

    return json;
  }

  return vm;
}

您的itemView將直接使用此視圖模型。


MyItemView = Backbone.Marionette.ItemView.extend({
  template: "#my-item-view-template",

  initialize: function(){

    // replace the model with the the view model
    this.model = createViewModel(this.model);

  }
});

MyCollectionView = Backbone.Marionette.CollectionView({
  itemView: MyItemView
});

就是這樣。

將集合傳遞給MyCollectionView構造函數並呈現集合視圖時,將在實例化MyCollectionView為每個itemView實例創建新的視圖模型。 模板現在可以從模型中呈現index

視圖模型直接從原始模型繼承,因此所有方法和屬性仍然可用。 覆蓋toJSON方法允許您從原始模型中獲取原始json,然后使用您需要的任何數據對其進行擴充。 您的原始模型永遠不會被修改,但項目視圖正在使用的模型具有您需要的數據。

暫無
暫無

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

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