2012-01-13 133 views
14

如何將骨幹視圖綁定到集合而不是模型?我是否需要將模型中的集合包裝起來?爲集合創建骨幹視圖

例如

如果我有一個骨幹模型客戶,並且這些客戶稱爲

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() })); 

然後我可以。這是正確的方式去做這件事嗎?我期望這是一個常見的情況,但我找不到任何例子,我是否以錯誤的方式去做?

回答

13

是的,你需要傳遞包裝的集合。

阿迪奧斯馬尼在他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); 
    }); 
    } 
}); 
+0

在最後一個例子中,你需要'var this = this;'在initialize方法的頂部嗎? – dubilla 2013-09-19 17:13:00

+1

@dubilla不,主幹將代碼下劃線方法的上下文設置爲'this'。 – EleventyOne 2013-10-14 02:13:19

+0

爲什麼'this._donutViews = [];'有一個下劃線字符? – fortuneRice 2013-10-17 04:28:11