2012-09-10 42 views
0

我有一個應用程序,它顯示框內的框。每個盒子模型都有一個方法'children',它返回盒子內顯示的任何方框。我想要做的是點擊一個按鈕,讓孩子呈現爲一個表格,其屬性列在幾列中。如何使用下劃線和骨幹代表HTML模型屬性

我不太確定如何做到這一點。我覺得下劃線模板可能是這個樣子:

<table class='list-items-template'> 
      <tr> 
      <td><%= this.model.ITSCHILDX.get('image') %>  </td> 
      <td><%= this.model.ITSCHILDX.get('title') %>  </td> 
      <td><%= this.model.ITSCHILDX.get('description') %> </td> 
      </tr> 
     </table> 

但隨後箱視圖中,我必須說,每個孩子都應該在表中插入,並且它的每一個屬性應代表的某種方式。幫助是大大讚賞。

+0

骨幹,你必須使用* *獲取函數可以訪問模型的屬性:http://backbonejs.org/#Model-get – elevine

+0

是的,我會更新的例子,但那不是我正在努力的。 –

回答

1

不知道我是否正確理解設置,但您有BoxModel。

BoxModel = Backbone.Model.extend({ 
    defaults: { 
     'image':string, 
     'title':string, 
     'description':string 
    } 
}); 

而一個BoxModel可以包含兒童BoxModels?

boxModel.children = new Collection(); // of box models? 

而且您想遍歷子集合並將每個模型表示爲表格行?

如果這是你想要的,這裏是我會做的。盒子模型由BoxView表示,它是一個表格,其子節點基本上表示爲行。所以我們將其定義爲:

BoxView = Backbone.View.extend({ 
    tagName: 'table', 
    className: 'list-items-template', // I just used this name to connect it with your ex. 
             // I'd probably change it to like, box-table 
    template: _.template('<tr> 
     <td><%= image %>  </td> 
     <td><%= title %>  </td> 
     <td><%= description %> </td> 
     </tr>'), 
    initialize: function() { 
     // Note: We've passed in a box model and a box model has a property called 
     // children that is a collection of other box models 
     this.box = this.model; 
     this.collection = this.box.children // Important! Assumes collection exists. 
    }, 
    render: function() { 
     this.$el.html(this.addAllRows()); 
     return this; 
    }, 
    addAllRows: function() { 
     var that = this; 
     var rows = ''; 
     this.collection.each(function(box) { 
      rows += that.template(box.toJSON()); 
     }); 
     return rows; 
    } 
}); 


// This assumes that whatever BoxModel you have instantiated, it has a property called 
// children that is a collection of other BoxModels. We pass this in. 

// Get the party started 
var myBoxTable = new BoxView({ 
    'model': someBoxModel // Your box model, it has a collection of children boxModels 
}); 

// Throw it into your page wherever. 
$('#placeToInsert').html(myBoxTable.render.el()); 

另外請注意,這基本上意味着您的孩子boxModels在此示例中可視化表示。如果每個孩子(行)必須具有一些功能,而不是僅僅使用模板寫出可視表示,我會使用addAllRows()方法來實例化第二種類型的BoxModel視圖。一個視圖,它是一個表格行,並具有更多的功能,如正確委派的事件。

2

您可以通過在模板中插入代碼塊來將迭代邏輯添加到模板中。要修改例如:

<table class='list-items-template'> 
    <% for (var idx in this.model.ITSCHILDX) { %> 
     <tr> 
      <td><%= this.model.ITSCHILDX[idx].get('image') %></td>  
      <td><%= this.model.ITSCHILDX[idx].get('title') %></td>  
      <td><%= this.model.ITSCHILDX[idx].get('description') %></td>  
     </tr> 
    <% } %> 
</table> 
+1

++簡明。可能想要循環內部的雖然正確嗎? ;-) – jmk2142