我是一个初学者与Backbone.js,我有麻烦,使一个一对多的关系之间的两个骨干模型,并显示这个数据到一个HTML标签行。我正在使用一台可以有多个订单的机器。数据看起来像:
机器和订单都配有FKmachine_id。我试图使TR元素与第一个元素TH是机器,并在第二/第三TH我想显示属于机器的订单。
所以我要问的问题是:
以下是订单和机器的模型:
app.Machine = Backbone.Model.extend({
defaults : {
machine_id : "",
status : "",
description : "",
},
});
app.Order = Backbone.Model.extend({
defaults: {
order_id: "",
description: "",
amount: "",,
begin_date:"",
end_date:"",
machine_id: ""
},
});
app.MachineList = Backbone.Collection.extend({
model: app.Machine
});
意见:
app.MachineView = Backbone.View.extend({
className: 'MachineRow',
template: _.template($('#Machine_Template').html()),
render: function(){
this.$el.html(this.template(this.model.attributes));
return this;
}
});
app.MachineListView = Backbone.View.extend({
el: '#Machine',
initialize: function(initialMachine){
this.collection = new app.MachineList(initialMachine);
this.render();
},
render: function(){
this.collection.each(function(item){
this.renderMachine(item);
filterOrder(item.get('machine_id'));
}, this);
},
renderMachine: function(item){
var machineView = new app.MachineView({
model: item
});
$(machineView.render().el).appendTo(this.$el)
}
});
超文本标记语言代码:将看起来像这样??
<script id="machine_template" type="text/template">
<th>
<%= machine_id %> //etc
</th>
<th>
<%= order_id %> //etc
</th>
<th>
<%= order_id %> //etc
</th>
</script>
假设您有一个名为订单
的订单集合,您可以执行以下操作:
let renderData = machineList.map(machine -> {
return {
machine: machine,
orders: orders.where({machine_id: machine.get('id')}
}
});
这应该给你一个类似于
[{
machine: machineModel1,
orders: [orderModel1, orderModal2]
},{
machine: machineModel2,
orders: [orderModel3, orderModal4]
}]
现在,您可以将其传递给模板函数,该函数迭代每个条目并呈现它。
我看到您已经通过在应用程序中引用您的机器id
建立了一对多关系。订购型号,至于你的第二个问题,
如何在下划线模板中创建此TR元素以显示属于机器的订单。
我看不到
在主干网中,模板只是一个不支持逻辑的哑html组件。所有逻辑都将驻留在视图中,理想情况下,您可以拥有订单集合,并通过machine\u id
字段查询订单集合。