【问题标题】:Managing multiple views for a Backbone collection管理 Backbone 集合的多个视图
【发布时间】:2013-07-11 17:04:31
【问题描述】:

我正在创建一个 Backbone 应用程序,其中包含用于查看报告的部分;该部分包含三个部分:报告链接菜单、显示报告的标题和显示报告的内容。用户将单击报告链接,该链接将获取相关模型的数据。然后报告标题和内容应相应更新。但是,我不确定视图绑定应该如何工作,并且每个报告可能返回稍微不同的数据,需要不同的视图模板。这是我的JSFiddle(仅在此示例中覆盖了 fetch 方法)

现在,我为每个报告都有一个 Backbone 模型和所有报告的 Backbone 集合:

App.Models.Report = Backbone.Model.extend();

App.Collections.Reports = Backbone.Collection.extend({
    model: App.Models.Report,
    url: "/reports"
});

菜单视图与集合相关联,单击时设置App.State.titleApp.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。此提取使用报告行的子集合填充模型。报告内容视图然后根据子集合数据设置它的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 的视图模板。我可以考虑将它存储在模型上,但模板应该与视图相关联。

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    如果您的cids 都由 HTML ids 中的合法字符组成,那么一个简单的解决方案是将所有报告模板命名为 templateReportxxx,其中“xxx”是报告的 cid然后只需将模板加载行更改为

    var template = _.template($('#templateReport'+cid).html());
    

    【讨论】:

    • 非常感谢您提供的简单解决方案!我实现了它,然后将我所有的 cid 引用更改为 ids,以便我可以控制这些引用。
    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2014-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多