在開始之前可以到 JSFiddle 取得範例程式碼並一邊閱讀底下的介紹。
環境的基本與過去大致相同:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html lang="en-US"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Learning About Backbone.js Collection</title> | |
</head> | |
<body> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> | |
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script> | |
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script> | |
<script> | |
/* Put your code here */ | |
</body> | |
</html> |
Collection 簡單來說就是一組 Model 的陣列版本,如果有一堆 Model 需要被當做陣列(或類似的有序資料結構 - ordered set)來操作,而更重要的是,Collection 可以無縫的整合 RESTful web service,大大減低與後端溝通的阻礙。此外,Collection 可以直接對監聽 Collection 本身或 Collection 裡的 Model 所發出的各種事件(event),例如 change, add, remove 等等。
來看看底下這個例子,假設我們有一種 Model 叫做 Person:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Person = Backbone.Model.extend({ | |
initialize: function() { | |
console.log('Person is initialized.'); | |
}, | |
defaults: { | |
name: 'undefined', | |
age: 'undefined' | |
} | |
}); |
如果我們想要有一個代表一群人的物件,可以用 Collection 建出代表一群人的 Collection: people,只要在建構的屬性裡面指定 Model 為 Person 即可:
產生一個 Person 或 People 的方法就像我們過去所知道的方法類似:
從 People (人群) 增加一個 Person (人)的方法:
people.add(person);
或是一些人
people.add([{name:"Bob"}, {name:"Jim"}]);
除此之外,也可以把 Collection 當做堆疊(stack),透過 push/pop 來操做:
people.push([{name:"Bob"}, {name:"Jim"}]);
people.pop();
也可以用 reset 來新增 Model。reset 和 add 唯一的差別在於 reset 會清除掉原本的所有 Model:
people.reset([{name:"Bob"}, {name:"Jim"}]);
/* 或是 */
people.reset([{name:"Bob"}, {name:"Jim"}], person);
想刪除一些人也沒問題:
people.remove(person);
值得注意的是上面的 add, reset 和 remove 都會觸發本身的事件(add, reset, remove event),我們可以用 on 這方法來監聽這些 event,例如
people.on('reset', function(){});
還有一些存取 Model 的方法,包括 at 和 getCid 等。at 這方法可以直接依照 Collection 裡面的 Model 生成的順序讀取,像是:
people.at(1);
Collection 的每一個 Model 都會有一串代表 Model 的 Cid,編號方式是 c 加上數字,例如 c1, c2。可以透過 getCid 來取出 model
people.getCid('c1');
除了上面方法來存取每個 Model 之外,也可以用 Models 來直接存取 Collection 的內容,例如:
console.log(people.models);
當然,要把整個 Collection 轉成 JSON 也只要呼叫一個方法即可:
people.toJSON();
若要讓 Collection 裡面的 Model 有排序,可以定義 comparator 這個屬性:
上面的例子,我們傳進了兩個 person, person2,取出 person 的 name 屬性作比較 如此一來 collection 的 getter/setter 就會按照 name 的排序來增減。 可以透過呼叫 sort() 來取強迫 collection 排序:
people.sort();
Collection 有一些特殊的過濾方法,其中一個是 pluck,可以從 Collection 中取出每個 Model 的某相同 key 的值的陣列。
例如上例中的 people 有三個 person,我們可以取出一個三個 person name 的 array:
people.pluck('name');
結果是
['Joe', 'Bob', 'Jim']
另外一個過濾方法是 where,可以藉由指定某種物件,找到 Collection 當中包含該物件的陣列。 假設我們有一個物件 friends:
透過 where:
var musketeers = friends.where({job: "Musketeer"});
我們可以得到 musketeers.length 的長度是3。
最後,是結合 RESTful web servcie 的操作,可以透過指定 url 屬性來對應到 RESTful API,例如:
上面這個例子的 People 會從 '/friends' 這個位置取得 JSON 資料,利用 guys.fetch() 就可以把資料讀進 Collection 裡面,而不必再另外 GET 資料並逐筆塞入 Collection,大大的簡化了存取或操作資料所需的瑣碎流程,是不是很棒呢?
Collection 是一個非常實用的 Backbone 物件,相信看完上面的例子之後,對於 Collection 的使用已經不再陌生。如果還想知道更多細節,歡迎參考官方說明文件,相信能讓您寫起 code 來如虎添翼!
Happy Coding!
延伸閱讀

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var People = Backbone.Collection.extend({ | |
initialize: function() { | |
console.log("People Collection is initialized"); | |
}, | |
model: Person | |
}); |
產生一個 Person 或 People 的方法就像我們過去所知道的方法類似:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var person = new Person({name:"Joe"}); | |
var people = new People(person); |
從 People (人群) 增加一個 Person (人)的方法:
people.add(person);
或是一些人
people.add([{name:"Bob"}, {name:"Jim"}]);
除此之外,也可以把 Collection 當做堆疊(stack),透過 push/pop 來操做:
people.push([{name:"Bob"}, {name:"Jim"}]);
people.pop();
也可以用 reset 來新增 Model。reset 和 add 唯一的差別在於 reset 會清除掉原本的所有 Model:
people.reset([{name:"Bob"}, {name:"Jim"}]);
/* 或是 */
people.reset([{name:"Bob"}, {name:"Jim"}], person);
想刪除一些人也沒問題:
people.remove(person);
值得注意的是上面的 add, reset 和 remove 都會觸發本身的事件(add, reset, remove event),我們可以用 on 這方法來監聽這些 event,例如
people.on('reset', function(){});
還有一些存取 Model 的方法,包括 at 和 getCid 等。at 這方法可以直接依照 Collection 裡面的 Model 生成的順序讀取,像是:
people.at(1);
Collection 的每一個 Model 都會有一串代表 Model 的 Cid,編號方式是 c 加上數字,例如 c1, c2。可以透過 getCid 來取出 model
people.getCid('c1');
除了上面方法來存取每個 Model 之外,也可以用 Models 來直接存取 Collection 的內容,例如:
console.log(people.models);
當然,要把整個 Collection 轉成 JSON 也只要呼叫一個方法即可:
people.toJSON();
若要讓 Collection 裡面的 Model 有排序,可以定義 comparator 這個屬性:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var People = Backbone.Collection.extend({ | |
model: Person, | |
comparator: function(person, person2) { | |
return person.get('name') < person2.get('name'); | |
} | |
}); |
上面的例子,我們傳進了兩個 person, person2,取出 person 的 name 屬性作比較 如此一來 collection 的 getter/setter 就會按照 name 的排序來增減。 可以透過呼叫 sort() 來取強迫 collection 排序:
people.sort();
Collection 有一些特殊的過濾方法,其中一個是 pluck,可以從 Collection 中取出每個 Model 的某相同 key 的值的陣列。
例如上例中的 people 有三個 person,我們可以取出一個三個 person name 的 array:
people.pluck('name');
結果是
['Joe', 'Bob', 'Jim']
另外一個過濾方法是 where,可以藉由指定某種物件,找到 Collection 當中包含該物件的陣列。 假設我們有一個物件 friends:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var friends = new Backbone.Collection([ | |
{name: "Athos", job: "Musketeer"}, | |
{name: "Porthos", job: "Musketeer"}, | |
{name: "Aramis", job: "Musketeer"}, | |
{name: "d'Artagnan", job: "Guard"}, | |
]); |
透過 where:
var musketeers = friends.where({job: "Musketeer"});
我們可以得到 musketeers.length 的長度是3。
最後,是結合 RESTful web servcie 的操作,可以透過指定 url 屬性來對應到 RESTful API,例如:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var People = Backbone.Collection.extend({ | |
model: Person, | |
url: '/friends' | |
}); | |
var guys = new People; | |
guys.fetch(); |
上面這個例子的 People 會從 '/friends' 這個位置取得 JSON 資料,利用 guys.fetch() 就可以把資料讀進 Collection 裡面,而不必再另外 GET 資料並逐筆塞入 Collection,大大的簡化了存取或操作資料所需的瑣碎流程,是不是很棒呢?
Collection 是一個非常實用的 Backbone 物件,相信看完上面的例子之後,對於 Collection 的使用已經不再陌生。如果還想知道更多細節,歡迎參考官方說明文件,相信能讓您寫起 code 來如虎添翼!
Happy Coding!
延伸閱讀
- 幫你的網頁加上Backbone(.js)(一): Model
- 幫你的網頁加上Backbone(.js)(二): View
- 幫你的網頁加上Backbone(.js)(三): Router
- 幫你的網頁加上Backbone(.js)(四): Collection
- 幫你的網頁加上Backbone(.js)(五): AJAX

沒有留言:
張貼留言