如何使用Undercore和Backbone在HTML中表示模型属性
How to represent model attributes wtihin HTML using Underscore and Backbone
我有一个应用程序,它显示框中框。每个框模型都有一个方法"children",该方法返回框中显示的任何框。我想做的是单击一个按钮,将子项呈现为一个表,其属性列在几列中。
我真的不知道该怎么做。我认为Undercore模板可能看起来像这样:
<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>
但是,在Box视图中,我需要用某种方式来表示每个子项都应该插入到表中,并且应该表示它的每个属性。非常感谢您的帮助。
您可以通过在模板中插入代码块来将迭代逻辑添加到模板中。修改您的示例:
<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>
不确定我是否正确理解设置,但您有一个BoxModel。
BoxModel = Backbone.Model.extend({
defaults: {
'image':string,
'title':string,
'description':string
}
});
BoxModel可以包含子BoxModel吗?
boxModel.children = new Collection(); // of box models?
您想遍历children集合并将每个模型表示为表行吗?
如果这是你想要的,我会这么做。一个盒子模型由一个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());
还要注意,这基本上意味着您的子boxModel在本例中以视觉方式表示。如果每个子(行)都必须具有一些功能,而不是仅仅使用模板来编写可视化表示,我会使用addAllRows()
方法来实例化第二种类型的BoxModel视图。一个视图,它是一个表行,具有更多的功能,如正确委派的事件。
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- React中的数据集表示
- 为集合分配大量的模型弹药
- 如何使用backbone.js从集合中获取模型名称
- 骨干模型默认值-todos.js示例中不必要的代码
- EmberJS中支持单字母单词模型
- 2个backbone.js集合,具有相同的模型,但排序顺序不同
- 将不在模型中的数据返回到mvc控制器
- 如何使用Undercore和Backbone在HTML中表示模型属性
- 如何在ember数据模型中表示数组
- AngularJS添加表示数组模型的输入
- Ember.js:如何表示一个有多个模型的关系
- 有没有办法轻松获取 C# 模型的 JavaScript 表示形式
- 将复选框的默认值绑定到角度模型,其中true和amp;false表示为'是'&'没有'
- 骨干关系型,使用mysql数据将模型表示为表行
- ngRepeat-ed 指令表示外部模型的字段
- EXT JS 5:如何将java表单表示为EXT JS模型
- 创建具有嵌套对象的复杂表单的JSON表示,并更新骨干模型
- 挖空视图模型,用于表示单个对象
- Backbone JS:集合视图中表示模型的参数从何而来?