【问题标题】:Creating a backbone view for a collection为集合创建主干视图
【发布时间】:2012-01-13 00:25:10
【问题描述】:

如何将主干视图绑定到集合而不是模型?我需要将集合包装在模型中吗?

例如

如果我有一个主干模型 Client 和一组称为 Clients 的集合

Client = Backbone.Model.extend({
    defaults: {
        Name: ''
    }
});

Clients = Backbone.Collection.extend({
    model: Client,
    url: 'Clients'
});

还有风景

    var ClientListView = Backbone.View.extend({
        template: _.template($("#clients-template").html()),
        el: $('#clientlist'),

        initialize: function() {
            _.bindAll(this, 'render');

            this.collection = new Clients();
        },

        render: function( event ){
            $(this.el).html(this.template({ this.collection.toJSON()));

            return this;
        }
    });

那么我无法访问下划线模板中的每个客户端元素。但是,如果我像这样包装集合

$(this.el).html(this.template({ clients: this.collection.toJSON() }));

那我可以。这是解决这个问题的正确方法吗?我希望这是一个常见的场景,但我找不到任何例子,我是不是走错了路?

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

    是的,你需要传递包装好的集合。

    Addy Osmani 在他的 Backbone Fundamentals 示例中使用了类似的方法 - 参见例如 this view 和相应的 template

    在视图中:

    $el.html( compiled_template( { results: collection.models } ) );
    

    在模板中:

    <% _.each( results, function( item, i ){ %>
       ...
    <% }); %>
    

    另一种选择是拥有一个视图,该视图将为集合中的每个模型创建单独的视图。以下是来自An Intro to Backbone.js: Part 3 – Binding a Collection to a View 的示例:

    var DonutCollectionView = Backbone.View.extend({
      initialize : function() {
        this._donutViews = [];
        this.collection.each(function(donut) {
          that._donutViews.push(new UpdatingDonutView({
            model : donut,
            tagName : 'li'
          }));
        });
      },
    
      render : function() {
        var that = this;
        $(this.el).empty();
    
        _(this._donutViews).each(function(dv) {
          $(that.el).append(dv.render().el);
        });
      }
    });
    

    【讨论】:

    • 上个例子中的初始化方法顶部是否需要var that = this;
    • @dubilla 不,主干将上下文设置为 this 用于代理下划线方法。
    • 为什么this._donutViews = []; 有下划线?
    • @fortuneRice 这只是在 JavaScript 中表示私有变量的约定。由于 JavaScript 没有明确的方式来定义私有成员,因此这种约定很常见,可以将其与公共成员区分开来。
    • 在大多数情况下,第二个不是理想的吗?渲染中所有与视觉相关的功能都被利用了,而第一个没有?
    【解决方案2】:

    您可能想看看backbone collectionView

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 2015-01-31
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多