標籤:
在前面我們的 Backbone.js 用上了 Model, 但絕大數的情況下我們處理的都是一批的 Model 資料列表,所以需要有一個 Collection 來容納 Model, 就像 Java 裡最常用的 List。
聲明 Collection 時需要指定他處理的 Model 類型,也就是個泛型參數,如我們這樣定義 Collection:
//define Collectionvar PeopleCollection = Backbone.Collection.extend({ model: Person //like generic});
然後就是往 Collection 中如何填充 Model 執行個體,有好多種,這裡只示範最直接的方式。還 add, fetch, 及對 Collection 排序, 遍曆等各種操作。
//create collection instancevar peopleCollection = new PeopleCollection([ { name: ‘Mohit Jain‘, age: 23 }, { name: ‘Taroon Tyagi‘, age: 25, }]);
在建立 View 執行個體時把 collection 傳遞進去
var peopleView = new PeopleView({collection: peopleCollection});
模板中使用的是點操作符來擷取屬性,所以交給模板顯示資料時需調用 Collection 的 toJSON() 轉資料,即把欄位從 attributes 中提出到外層來。在 View 中需要這樣綁定集合資料:
var data = {people: this.collection.toJSON()};this.$el.html(template(data)); //fill in data
模板中可用 _.each() 函數來遍曆:
<% _.each(people, function(person) { %> <li><%= person.name %>, <%= person.age %></li> <% }); %>
這樣就能把 Collection 中的資料顯示到頁面上了,完整例子如下:
<!DOCTYPE html><html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js"></script> </head> <body> <ol id="container"></ol> <script type="text/template" id="person_template"> <% _.each(people, function(person) { %> <li><%= person.name %>, <%= person.age %></li> <% }); %> </script> </body> </html> <script> //define Model var Person = Backbone.Model.extend({ defaults : { name : ‘unknown‘, age : 20 } }); //define Collection var PeopleCollection = Backbone.Collection.extend({ model: Person //like generic }); //define View var PeopleView = Backbone.View.extend({ el: ‘#container‘, initialize: function(options) { this.render(); }, render: function() { var template = _.template($("#person_template").html()); var data = {people: this.collection.toJSON()}; this.$el.html(template(data)); //fill in data } }); //create collection instance var peopleCollection = new PeopleCollection([ { name: ‘Mohit Jain‘, age: 23 }, { name: ‘Taroon Tyagi‘, age: 25, } ]); //create view and bind model var peopleView = new PeopleView({collection: peopleCollection}); </script>
點選連結 http://fiddle.jshell.net/Unmi/NeNsU/ 運行如上代碼,頁面輸出為:
- Mohit Jain, 23
- Taroon Tyagi, 25
上面用的是 Underscore 的模板,在頁面中可以單獨的用 <% _.each([0,1,2,3,4], function(i) { %> <p><%= i %></p> <% }); %> 遍曆數組 [0,1,2,3,4]。
本文連結 http://unmi.cc/backbone-js-with-collection/, 來自 隔葉黃鶯 Unmi Blog
Backbone.js 使用 Collection