## Backbone.Collection(集合)
集合是模型的有序組合,我們可以在集合上綁定 `"change"` 事件,從而當集合中的模型發生變化時`fetch`(獲得)通知,集合也可以監聽 `"add"` 和 `"remove"` 事件, 從服務器更新,并能使用 [Underscore.js](#Collection-Underscore-Methods) 提供的方法。
集合中的模型觸發的任何事件都可以在集合身上直接觸發,所以我們可以監聽集合中模型的變化: `documents.on("change:selected", ...)`
**extend**`Backbone.Collection.extend(properties, [classProperties])`
通過擴展 **Backbone.Collection** 創建一個 **Collection** 類。實例屬性參數 **properties** 以及 類屬性參數 **classProperties** 會被直接注冊到集合的構造函數。
**model**`collection.model`
覆蓋此屬性來指定集合中包含的模型類。可以傳入原始屬性對象(和數組)來 [add](#Collection-add), [create](#Collection-create),和 [reset](#Collection-reset),傳入的屬性會被自動轉換為適合的模型類型。
```
var Library = Backbone.Collection.extend({
model: Book
});
```
集合也可以包含多態模型,通過用構造函數重寫這個屬性,返回一個模型。
```
var Library = Backbone.Collection.extend({
model: function(attrs, options) {
if (condition) {
return new PublicDocument(attrs, options);
} else {
return new PrivateDocument(attrs, options);
}
}
});
```
**constructor / initialize**`new Backbone.Collection([models], [options])`
當創建集合時,你可以選擇傳入初始的 **models** 數組。 集合的 [comparator](#Collection-comparator) 函數也可以作為選項傳入。 傳遞`false`作為comparator選項將阻止排序。 如果定義了 **initialize** 函數,會在集合創建時被調用。 有幾個選項, 如果提供的話,將直接附加到集合上:`model` 和 `comparator`。
通過傳遞`null`給`models`選項來創建一個空的集合。
```
var tabs = new TabSet([tab1, tab2, tab3]);
var spaces = new Backbone.Collection([], {
model: Space
});
```
**models**`collection.models`
訪問集合中模型的內置的JavaScript 數組。通常我們使用 `get`, `at`,或 **Underscore方法** 訪問模型對象,但偶爾也需要直接訪問。
**toJSON**`collection.toJSON([options])`
返回集合中包含的每個模型(通過 [toJSON](#Model-toJSON)) 的屬性哈希的數組。可用于集合的序列化和持久化。本方法名稱容易引起混淆,因為它與 [JavaScript's JSON API](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior) 命名相同。
```
var collection = new Backbone.Collection([
{name: "Tim", age: 5},
{name: "Ida", age: 26},
{name: "Rob", age: 55}
]);
alert(JSON.stringify(collection));
```
**sync**`collection.sync(method, collection, [options])`
使用 [Backbone.sync](#Sync)來將一個集合的狀態持久化到服務器。 可以自定義行為覆蓋。
**Underscore 方法 (32)**
Backbone 代理了 **Underscore.js**用來給**Backbone.Collection**提供 6 個對象函數。這里沒有完全記錄他們,但你可以看看Underscore文檔中全部詳情…(愚人碼頭注:下面鏈接已經替換成中文文檔的地址)
* [forEach (each)](http://www.css88.com/doc/underscore/#each)
* [map (collect)](http://www.css88.com/doc/underscore/#map)
* [reduce (foldl, inject)](http://www.css88.com/doc/underscore/#reduce)
* [reduceRight (foldr)](http://www.css88.com/doc/underscore/#reduceRight)
* [find (detect)](http://www.css88.com/doc/underscore/#find)
* [filter (select)](http://www.css88.com/doc/underscore/#filter)
* [reject](http://www.css88.com/doc/underscore/#reject)
* [every (all)](http://www.css88.com/doc/underscore/#every)
* [some (any)](http://www.css88.com/doc/underscore/#some)
* [contains (include)](http://www.css88.com/doc/underscore/#contains)
* [invoke](http://www.css88.com/doc/underscore/#invoke)
* [max](http://www.css88.com/doc/underscore/#max)
* [min](http://www.css88.com/doc/underscore/#min)
* [sortBy](http://www.css88.com/doc/underscore/#sortBy)
* [groupBy](http://www.css88.com/doc/underscore/#groupBy)
* [shuffle](http://www.css88.com/doc/underscore/#shuffle)
* [toArray](http://www.css88.com/doc/underscore/#toArray)
* [size](http://www.css88.com/doc/underscore/#size)
* [first (head, take)](http://www.css88.com/doc/underscore/#first)
* [initial](http://www.css88.com/doc/underscore/#initial)
* [rest (tail, drop)](http://www.css88.com/doc/underscore/#rest)
* [last](http://www.css88.com/doc/underscore/#last)
* [without](http://www.css88.com/doc/underscore/#without)
* [indexOf](http://www.css88.com/doc/underscore/#indexOf)
* [lastIndexOf](http://www.css88.com/doc/underscore/#lastIndexOf)
* [isEmpty](http://www.css88.com/doc/underscore/#isEmpty)
* [chain](http://www.css88.com/doc/underscore/#chain)
* [difference](http://www.css88.com/doc/underscore/#difference)
* [sample](http://www.css88.com/doc/underscore/#sample)
* [partition](http://www.css88.com/doc/underscore/#partition)
* [countBy](http://www.css88.com/doc/underscore/#countBy)
* [indexBy](http://www.css88.com/doc/underscore/#indexBy)
```
books.each(function(book) {
book.publish();
});
var titles = books.map(function(book) {
return book.get("title");
});
var publishedBooks = books.filter(function(book) {
return book.get("published") === true;
});
var alphabetical = books.sortBy(function(book) {
return book.author.get("name").toLowerCase();
});
```
**add**`collection.add(models, [options])`
向集合中增加一個模型(或一個模型數組),觸發`"add"`事件。 ?如果已經定義了[model](#Collection-model)屬性, 您也可以通過原始屬性的對象讓其看起來像一個模型實例。 返回已經添加的(或預先存在的,如果重復)模式。 ?傳遞`{at: index}`可以將模型插入集合中特定的`index`索引位置。 如果您要添加 集合中已經存在的模型 到集合,他們會被忽略, 除非你傳遞`{merge: true}`, 在這種情況下,它們的屬性將被合并到相應的模型中, 觸發任何適當的`"change"` 事件。
```
var ships = new Backbone.Collection;
ships.on("add", function(ship) {
alert("Ahoy " + ship.get("name") + "!");
});
ships.add([
{name: "Flying Dutchman"},
{name: "Black Pearl"}
]);
```
請注意,添加相同的模型(具有相同`id`的模型)到一個集合,一次以上
是空操作。
**remove**`collection.remove(models, [options])`
從集合中刪除一個模型(或一個模型數組),并且返回他們。會觸發 `"remove"` 事件,同樣可以使用 `silent` 關閉。移除前該模型的index可用作`options.index`類監聽。
**reset**`collection.reset([models], [options])`
每次都是只添加和刪除一個模型那沒問題, 但有時,你需要改變很多模型,那么你寧愿只更新集合。 ?使用**reset**,將一個新的模型(或屬性散列)列表替換集合,最后觸發一個但單獨的`"reset"`事件。 到與模型的新列表替換集合(或屬性散列),觸發一個單一的“復位”事件在末端。 返回新的模型集合。 為方便起見, 在一個 `"reset"`事件中, 任何以前的模型列表可作為`options.previousModels`。
通過傳遞`null`給`models`選項來清空你的集合。
下面是一個例子 使用**reset**來引導一個集合在頁面初始化時加載, 在Rails應用程序中:
```
<script>
var accounts = new Backbone.Collection;
accounts.reset(<%= @accounts.to_json %>);
</script>
```
調用`collection.reset()`,不傳遞任何模型作為參數 將清空整個集合。
**set**`collection.set(models, [options])`
**set**方法通過傳遞模型列表執行一個集合的"smart(智能)"的更新。 如果列表中的一個模型尚不在集合中,那么它將被添加; 如果模型已經在集合中,其屬性將被合并; 并且如果集合包含_不_存在于列表中的任何模型,他們將被刪除。 以上所有將觸發相應的`"add"`, `"remove"`, 和 `"change"`事件。 返回集合中的模型。 如果您想自定義的行為, 你可以設置選項:`{add: false}`, `{remove: false}`, 或 `{merge: false}`,將其禁用。
```
var vanHalen = new Backbone.Collection([eddie, alex, stone, roth]);
vanHalen.set([eddie, alex, stone, hagar]);
// Fires a "remove" event for roth, and an "add" event for "hagar".
// Updates any of stone, alex, and eddie's attributes that may have
// changed over the years.
```
**get**`collection.get(id)`
通過一個[id](#Model-id),一個[cid](#Model-cid),或者傳遞一個**model**來 獲得集合中 的模型。
```
var book = library.get(110);
```
**at**`collection.at(index)`
獲得集合中指定索引的模型。不論你是否對模型進行了重新排序, **at** 始終返回其在集合中插入時的索引值。
**push**`collection.push(model, [options])`
在集合尾部添加一個模型。選項和[add](#Collection-add)相同。
**pop**`collection.pop([options])`
刪除并且返回集合中最后一個模型。選項和[remove](#Collection-remove)相同。
**unshift**`collection.unshift(model, [options])`
在集合開始的地方添加一個模型。選項和[add](#Collection-add)相同。
**shift**`collection.shift([options])`
刪除并且返回集合中第一個模型。選項和[remove](#Collection-remove)相同。
**slice**`collection.slice(begin, end)`
返回一個集合的模型的淺拷貝副本,使用與原生[Array#slice](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)相同的選項。
**length**`collection.length`
與數組類似,集合擁有 `length` 屬性,返回該集合包含的模型數量。
**comparator**`collection.comparator`
默認情況下,集合沒有聲明 **comparator** 函數。如果定義了該函數,集合中的模型會按照指定的算法進行排序。 換言之,被增加模型,會被插入 `collection.models`中適合的位置。 comparator可以被定義為[sortBy](http://www.css88.com/doc/underscore/#sortBy)(傳遞帶有一個參數的函數), ?作為一個[sort](https://developer.mozilla.org/JavaScript/Reference/Global_Objects/Array/sort)(傳遞一個一個參數函數需要兩個參數), 或者作為一個表示屬性的字符串進行排序。
"sortBy"比較函數接受一個模型,并且返回一個該模型相對于其他模型的排序數字或字符串值。 ?"sort"比較函數接受兩個模型,并且,如果第一個模型應該在第二模型個之前,返回`-1`; 如果他們是同一等級的,返回`0`; 如果第一個模型應該在第二模型個之后,返回`1`; _需要注意的是 Backbone 這兩種風格的比較功能的確定 取決于參數個數。所以如果你綁定了比較函數,需要格外小心。_
注意即使下面例子中的 chapters 是后加入到集合中的,但它們都會遵循正確的排序:
```
var Chapter = Backbone.Model;
var chapters = new Backbone.Collection;
chapters.comparator = 'page';
chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));
alert(chapters.pluck('title'));
```
如果以后更改模型屬性,帶有比較函數的集合不會自動重新排序。 所以你不妨改變模型的屬性后調用`sort`, 這會影響排序。
**sort**`collection.sort([options])`
強制對集合進行重排序。一般情況下不需要調用本函數,因為當一個模型被添加時, [comparator](#Collection-comparator) 函數會實時排序。要禁用添加模型時的排序,可以傳遞`{sort: false}`給`add`。 調用**sort**會觸發的集合的`"sort"`事件。
**pluck**`collection.pluck(attribute)`
從集合中的每個模型中拉取 attribute(屬性)。等價于調用 `map`,并從迭代器中返回單個屬性。
```
var stooges = new Backbone.Collection([
{name: "Curly"},
{name: "Larry"},
{name: "Moe"}
]);
var names = stooges.pluck("name");
alert(JSON.stringify(names));
```
**where**`collection.where(attributes)`
返回集合中所有匹配所傳遞 **attributes**(屬性)的模型數組。 對于簡單的`filter(過濾)`比較有用。
```
var friends = new Backbone.Collection([
{name: "Athos", job: "Musketeer"},
{name: "Porthos", job: "Musketeer"},
{name: "Aramis", job: "Musketeer"},
{name: "d'Artagnan", job: "Guard"},
]);
var musketeers = friends.where({job: "Musketeer"});
alert(musketeers.length);
```
**findWhere**`collection.findWhere(attributes)`
就像[where](#Collection-where), 不同的是**findWhere**直接返回匹配所傳遞 **attributes**(屬性)的第一個模型。
**url**`collection.url or collection.url()`
設置 **url** 屬性(或函數)以指定集合對應的服務器位置。集合內的模型使用 **url** 構造自身的 URLs。
```
var Notes = Backbone.Collection.extend({
url: '/notes'
});
// Or, something more sophisticated:
var Notes = Backbone.Collection.extend({
url: function() {
return this.document.url() + '/notes';
}
});
```
**parse**`collection.parse(response, options)`
每一次調用 [fetch](#Collection-fetch) 從服務器拉取集合的模型數據時,**parse**都會被調用。 本函數接收原始 `response` 對象,返回可以 [added(添加)](#Collection-add) 到集合的模型屬性數組。 默認實現是無需操作的,只需簡單傳入服務端返回的JSON對象。 如果需要處理遺留API,或者在返回數據定義自己的命名空間,可以重寫本函數。
```
var Tweets = Backbone.Collection.extend({
// The Twitter Search API returns tweets under "results".
parse: function(response) {
return response.results;
}
});
```
**clone**`collection.clone()`
返回一個模型列表完全相同的集合新實例。
**fetch**`collection.fetch([options])`
從服務器拉取集合的默認模型設置 ,成功接收數據后會[setting(設置)](#Collection-set)集合。 **options** 支持 `success` 和 `error` 回調函數,兩個回調函數接收 `(collection, response, options)`作為參數。當模型數據從服務器返回時, 它使用 [set](#Collection-set)來(智能的)合并所獲取到的模型, 除非你傳遞了 `{reset: true}`, 在這種情況下,集合將(有效地)重置。 可以委托[Backbone.sync](#Sync) 在幕后自定義持久性策略 并返回一個[jqXHR](http://www.css88.com/jqapi-1.9/jQuery.ajax/#jqXHR)。 **fetch**請求的服務器處理器應該返回模型JSON數組。
```
Backbone.sync = function(method, model) {
alert(method + ": " + model.url);
};
var accounts = new Backbone.Collection;
accounts.url = '/accounts';
accounts.fetch();
```
**fetch**行為可以通過使用有效的[set](#Collection-set)選項進行定制。 例如,要獲取一個集合,每一個新的模型會得到一個 `"add"`事件,和每改變現有的模型的 `"change"`事件, 不刪除任何東西: `collection.fetch({remove: false})`
**jQuery.ajax**選項也可以直接傳遞作為 **fetch**選項, 所以要獲取一個分頁集合的特定頁面使用:`Documents.fetch({data: {page: 3}})`。
需要注意的是 **fetch** 不應該被用來在頁面加載完畢時填充集合數據 — 所有頁面初始數據應當在 [bootstrapped](#FAQ-bootstrap) 時已經就緒。 **fetch** 適用于惰性加載不需立刻展現的模型數據:例如:例如文檔中 可切換打開和關閉的選項卡內容。
**create**`collection.create(attributes, [options])`
方便的在集合中創建一個模型的新實例。 相當于使用屬性哈希(鍵值對象)實例化一個模型, 然后將該模型保存到服務器, 創建成功后將模型添加到集合中。 返回這個新模型。 如果客戶端驗證失敗,該模型將不會被保存, 與驗證錯誤。 為了能正常運行,需要在集合中設置 [model](#Collection-model) 屬性。 create 方法接收鍵值對象或者已經存在尚未保存的模型對象作為參數。
創建一個模型將立即觸發集合上的`"add"`事件, 一個`"request"`的事件作為新的模型被發送到服務器, 還有一個 `"sync"` ”事件,一旦服務器響應成功創建模型。 如果你想在集合中添加這個模型前等待服務器相應,請傳遞`{wait: true}`。
```
var Library = Backbone.Collection.extend({
model: Book
});
var nypl = new Library;
var othello = nypl.create({
title: "Othello",
author: "William Shakespeare"
});
```