我正在创建一个具有查看报告部分的主干应用程序;该部分有三个部分:报告链接菜单、所显示报告的标题和所显示报告的内容。用户将单击一个报告链接,这将获取相关模型的数据。然后,报告标题和内容应该相应地更新。但是,我不确定视图绑定应该如何工作,并且每个报告返回的数据可能略有不同,这些数据需要不同的视图模板。这是我的JSFiddle (fetch方法仅在本例中被覆盖)
现在,我有每个报告的主干模型和所有报告的主干集合:
App.Models.Report = Backbone.Model.extend();
App.Collections.Reports = Backbone.Collection.extend({
model: App.Models.Report,
url: "/reports"
});menu视图绑定到集合,并在单击时设置App.State.title和App.State.cid,其他两个视图正在侦听:
App.Views.ReportLink = Backbone.View.extend({
tagName: 'li',
className: 'is-clickable',
initialize: function() {
this.render();
},
render: function() {
this.el.innerHTML = this.model.get('title');
this.$el.attr('data-CID', this.model.cid); // store the model's cid
}
});
App.Views.ReportMenu = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.listenTo(this.collection, 'reset', this.render)
this.render();
this.$el.on('click', 'li', function() {
App.State.set({
'title': this.innerHTML,
'cid': $(this).attr('data-CID') // cid of the clicked view's model
});
});
},困难在于报告内容;它当前所做的是侦听App.State.cid的更改,然后使用该cid调用给定模型上的fetch。此fetch使用报告行的子集填充模型。然后,报表内容视图根据子集合数据设置其html,并且还应将正确的模板应用于数据:
App.Views.ReportContent = Backbone.View.extend({
initialize: function(attrs) {
this.listenTo(this.model, 'change:cid', this.render);
this.reportsCollection = attrs.reportsCollection;
},
render: function() {
var self = this,
cid = this.model.get('cid'),
model = this.reportsCollection.get(cid);
model.fetch({
success: function() {
var html = '';
model.subCollection.each(function(model) {
var template = _.template($('#templateReportA').html()); // want to dynamically set this
html += template(model.toJSON());
});
self.$el.html(html);
}
});
}
});1)对于这种具有集合的多视图情况,这是正确的实现类型吗?
2)如何传递每个报表需要申请的正确模板?现在,我显式地传递了报告A的视图模板。我可以考虑将其存储在模型上,但模板应该与视图相关联。
发布于 2013-07-13 17:54:49
如果您的cid都由在HTML id中合法的字符组成,那么一个简单的解决方案是将所有报表模板命名为templateReportxxx,其中"xxx“是报表的cid,然后将模板加载行更改为
var template = _.template($('#templateReport'+cid).html());https://stackoverflow.com/questions/17627032
复制相似问题