Collection
Extends:
Direct Subclass:
Indirect Subclass:
Backbone.Collection - Collections are ordered sets of models. (http://backbonejs.org/#Collection)
You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.js methods.
Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection, for example: documents.on("change:selected", ...)
Underscore methods available to Collection (including aliases):
See:
- http://underscorejs.org/#chain
- http://underscorejs.org/#contains
- http://underscorejs.org/#countBy
- http://underscorejs.org/#difference
- http://underscorejs.org/#each
- http://underscorejs.org/#every
- http://underscorejs.org/#filter
- http://underscorejs.org/#find
- http://underscorejs.org/#first
- http://underscorejs.org/#groupBy
- http://underscorejs.org/#indexBy
- http://underscorejs.org/#indexOf
- http://underscorejs.org/#initial
- http://underscorejs.org/#invoke
- http://underscorejs.org/#isEmpty
- http://underscorejs.org/#last
- http://underscorejs.org/#lastIndexOf
- http://underscorejs.org/#map
- http://underscorejs.org/#max
- http://underscorejs.org/#min
- http://underscorejs.org/#partition
- http://underscorejs.org/#reduce
- http://underscorejs.org/#reduceRight
- http://underscorejs.org/#reject
- http://underscorejs.org/#rest
- http://underscorejs.org/#sample
- http://underscorejs.org/#shuffle
- http://underscorejs.org/#some
- http://underscorejs.org/#sortBy
- http://underscorejs.org/#size
- http://underscorejs.org/#toArray
- http://underscorejs.org/#without
Example:
If using Backbone-ES6 by ES6 source one can create a module for a Backbone.Collection:
export default new Backbone.Collection(null,
{
model: Backbone.Model.extend(...)
});
or if importing a specific model class
import Model from '<MY-BACKBONE-MODEL>'
export default new Backbone.Collection(null,
{
model: Model
});
or use full ES6 style by using a getter for "model":
import Model from '<MY-BACKBONE-MODEL>'
class MyCollection extends Backbone.Collection
{
get model() { return Model; }
}
export default new MyCollection(); // If desired drop "new" to export the class itself and not an instance.
Constructor Summary
Public Constructor | ||
public |
constructor(models: Array<Model>, options: object) When creating a Collection, you may choose to pass in the initial array of models. |
Member Summary
Public Members | ||
public |
A comparator string indicating the attribute to sort. |
|
public |
The length of the models array. |
|
public |
The default Backbone.Model class to use as a prototype for this collection. |
|
public |
An array of models in the collection. |
Method Summary
Public Methods | ||
public |
Add a model (or an array of models) to the collection, firing an "add" event for each model, and an "update" event afterwards. |
|
public |
Get a model from a collection, specified by index. |
|
public |
clone(): Collection Returns a new instance of the collection with an identical list of models. |
|
public |
Convenience to create a new instance of a model within a collection. |
|
public |
Fetch the default set of models for this collection from the server, setting them on the collection when they arrive. |
|
public |
Just like |
|
public |
Get a model from a collection, specified by an id, a cid, or by passing in a model. |
|
public abstract |
Initialize is an empty function by default. |
|
public |
Override this method to specify the attribute the collection will use to refer to its models in collection.get. |
|
public |
|
|
public |
Pluck an attribute from each model in the collection. |
|
public |
Remove and return the last model from a collection. |
|
public |
Add a model at the end of a collection. |
|
public |
Remove a model (or an array of models) from the collection, and return them. |
|
public |
Adding and removing models one at a time is all well and good, but sometimes you have so many models to change that you'd rather just update the collection in bulk. Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end. Returns the newly-set models. For convenience, within a "reset" event, the list of any previous models is available as options.previousModels. Pass null for models to empty your Collection with options. Calling collection.reset() without passing any models as arguments will empty the entire collection. Here's an example using reset to bootstrap a collection during initial page load, in a Rails application: |
|
public |
The set method performs a "smart" update of the collection with the passed list of models. |
|
public |
Remove and return the first model from a collection. |
|
public |
slice(): * Return a shallow copy of this collection's models, using the same options as native |
|
public |
sort(options: object): Collection Force a collection to re-sort itself. |
|
public |
sync(): * Uses Backbone.sync to persist the state of a collection to the server. |
|
public |
Return an array containing the attributes hash of each model (via toJSON) in the collection. |
|
public |
Add a model at the beginning of a collection. |
|
public |
Return an array of all the models in a collection that match the passed attributes. |
Protected Methods | ||
protected |
_prepareModel(attrs: object, options: object): * Prepare a hash of attributes (or other model) to be added to this collection. |
|
protected |
_reset() Resets all internal state. |
Inherited Summary
From class Events | ||
public |
bind(): * Delegates to |
|
public |
Tell an object to listen to a particular event on an other object. |
|
public |
listenToOnce(obj: object, name: string, callback: function): Events Just like |
|
public |
Remove a previously-bound callback function from an object. |
|
public |
Bind a callback function to an object. |
|
public |
Just like |
|
public |
stopListening(obj: object, name: string, callback: function): Events Tell an object to stop listening to events. |
|
public |
Trigger callbacks for the given event, or space-delimited list of events. |
|
public |
unbind(): * Delegates to |
Public Constructors
public constructor(models: Array<Model>, options: object) source
When creating a Collection, you may choose to pass in the initial array of models. The collection's comparator may be included as an option. Passing false as the comparator option will prevent sorting. If you define an initialize function, it will be invoked when the collection is created. There are a couple of options that, if provided, are attached to the collection directly: model and comparator.
Pass null for models to create an empty Collection with options.
Override:
Events#constructorPublic Members
Public Methods
public add(models: Model | Array<Model>, options: object): * source
Add a model (or an array of models) to the collection, firing an "add" event for each model, and an "update" event afterwards. If a model property is defined, you may also pass raw attributes objects, and have them be vivified as instances of the model. Returns the added (or preexisting, if duplicate) models. Pass {at: index} to splice the model into the collection at the specified index. If you're adding models to the collection that are already in the collection, they'll be ignored, unless you pass {merge: true}, in which case their attributes will be merged into the corresponding models, firing any appropriate "change" events.
Note that adding the same model (a model with the same id) to a collection more than once is a no-op.
Return:
* |
Example:
var ships = new Backbone.Collection;
ships.on("add", function(ship) {
alert("Ahoy " + ship.get("name") + "!");
});
ships.add([
{name: "Flying Dutchman"},
{name: "Black Pearl"}
]);
public at(index: number): * source
Get a model from a collection, specified by index. Useful if your collection is sorted, and if your collection isn't sorted, at will still retrieve models in insertion order.
Params:
Name | Type | Attribute | Description |
index | number | Index for model to retrieve. |
Return:
* |
public clone(): Collection source
Returns a new instance of the collection with an identical list of models.
public create(attrs: Model, options: object): * source
Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the new model. If client-side validation failed, the model will be unsaved, with validation errors. In order for this to work, you should set the model property of the collection. The create method can accept either an attributes hash or an existing, unsaved model object.
Creating a model will cause an immediate "add" event to be triggered on the collection, a "request" event as the new model is sent to the server, as well as a "sync" event, once the server has responded with the successful creation of the model. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.
Return:
* |
Example:
var Library = Backbone.Collection.extend({
model: Book
});
var nypl = new Library;
var othello = nypl.create({
title: "Othello",
author: "William Shakespeare"
});
public fetch(options: object): * source
Fetch the default set of models for this collection from the server, setting them on the collection when they arrive. The options hash takes success and error callbacks which will both be passed (collection, response, options) as arguments. When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}, in which case the collection will be (efficiently) reset. Delegates to Backbone.sync under the covers for custom persistence strategies and returns a jqXHR. The server handler for fetch requests should return a JSON array of models.
The behavior of fetch can be customized by using the available set options. For example, to fetch a collection, getting an "add" event for every new model, and a "change" event for every changed existing model, without removing anything: collection.fetch({remove: false})
jQuery.ajax options can also be passed directly as fetch options, so to fetch a specific page of a paginated collection: Documents.fetch({data: {page: 3}})
Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place. fetch is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed.
Params:
Name | Type | Attribute | Description |
options | object | Optional parameters |
Return:
* |
Example:
Backbone.sync = function(method, model) {
alert(method + ": " + model.url);
};
var accounts = new Backbone.Collection;
accounts.url = '/accounts';
accounts.fetch();
public findWhere(attrs: object): * source
Just like where
, but directly returns only the first model in the collection that matches the passed
attributes.
Params:
Name | Type | Attribute | Description |
attrs | object | Attribute hash to match. |
Return:
* |
public get(obj: Model): * source
Get a model from a collection, specified by an id, a cid, or by passing in a model.
Params:
Name | Type | Attribute | Description |
obj | Model | An instance of a model to search for by object, id, or cid. |
Return:
* |
Example:
var book = library.get(110);
public abstract initialize() source
Initialize is an empty function by default. Override it with your own initialization logic.
public modelId(attrs: object): * source
Override this method to specify the attribute the collection will use to refer to its models in collection.get. By default returns the idAttribute of the collection's model class or failing that, 'id'. If your collection uses polymorphic models and those models have an idAttribute other than id you must override this method with your own custom logic.
Params:
Name | Type | Attribute | Description |
attrs | object | Attributes hash |
Return:
* |
Example:
var Library = Backbone.Collection.extend({
model: function(attrs, options) {
if (condition) {
return new PublicDocument(attrs, options);
} else {
return new PrivateDocument(attrs, options);
}
},
modelId: function(attrs) {
return attrs.private ? 'private_id' : 'public_id';
}
});
public parse(resp: object, options: object): object source
parse
is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is
passed the raw response object, and should return the array of model attributes to be added to the collection.
The default implementation is a no-op, simply passing through the JSON response. Override this if you need to
work with a preexisting API, or better namespace your responses.
Example:
var Tweets = Backbone.Collection.extend({
// The Twitter Search API returns tweets under "results".
parse: function(response) {
return response.results;
}
});
public pluck(attr: string): * source
Pluck an attribute from each model in the collection. Equivalent to calling map and returning a single attribute from the iterator.
Params:
Name | Type | Attribute | Description |
attr | string | Attribute key |
Return:
* |
Example:
var stooges = new Backbone.Collection([
{name: "Curly"},
{name: "Larry"},
{name: "Moe"}
]);
var names = stooges.pluck("name");
alert(JSON.stringify(names));
public pop(options: object): * source
Remove and return the last model from a collection. Takes the same options as remove.
Params:
Name | Type | Attribute | Description |
options | object | Optional parameters |
Return:
* |
public push(model: Model, options: object): * source
Add a model at the end of a collection. Takes the same options as add
.
Return:
* |
public remove(models: Model | Array<Model>, options: object): * source
Remove a model (or an array of models) from the collection, and return them. Each model can be a Model instance, an id string or a JS object, any value acceptable as the id argument of collection.get. Fires a "remove" event for each model, and a single "update" event afterwards. The model's index before removal is available to listeners as options.index.
Return:
* |
public reset(models: Array<Model>, options: object): * source
Adding and removing models one at a time is all well and good, but sometimes you have so many models to change that you'd rather just update the collection in bulk. Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end. Returns the newly-set models. For convenience, within a "reset" event, the list of any previous models is available as options.previousModels. Pass null for models to empty your Collection with options.
Calling collection.reset() without passing any models as arguments will empty the entire collection.
Here's an example using reset to bootstrap a collection during initial page load, in a Rails application:
Return:
* |
Example:
<script>
var accounts = new Backbone.Collection;
accounts.reset(<%= @accounts.to_json %>);
</script>
public set(models: Array<Model>, options: object): * source
The set method performs a "smart" update of the collection with the passed list of models. If a model in the list isn't yet in the collection it will be added; if the model is already in the collection its attributes will be merged; and if the collection contains any models that aren't present in the list, they'll be removed. All of the appropriate "add", "remove", and "change" events are fired as this happens. Returns the touched models in the collection. If you'd like to customize the behavior, you can disable it with options: {add: false}, {remove: false}, or {merge: false}.
Return:
* |
Example:
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.
public shift(options: object): * source
Remove and return the first model from a collection. Takes the same options as remove
.
Params:
Name | Type | Attribute | Description |
options | object | Optional parameters |
Return:
* |
public slice(): * source
Return a shallow copy of this collection's models, using the same options as native Array#slice
.
Return:
* |
public sort(options: object): Collection source
Force a collection to re-sort itself. You don't need to call this under normal circumstances, as a collection with a comparator will sort itself whenever a model is added. To disable sorting when adding a model, pass {sort: false} to add. Calling sort triggers a "sort" event on the collection.
Params:
Name | Type | Attribute | Description |
options | object | Optional parameters |
public sync(): * source
Uses Backbone.sync to persist the state of a collection to the server. Can be overridden for custom behavior.
Return:
* |
public toJSON(options: object): object source
Return an array containing the attributes hash of each model (via toJSON) in the collection. This can be used to serialize and persist the collection as a whole. The name of this method is a bit confusing, because it conforms to JavaScript's JSON API.
Params:
Name | Type | Attribute | Description |
options | object | Optional parameters |
Example:
var collection = new Backbone.Collection([
{name: "Tim", age: 5},
{name: "Ida", age: 26},
{name: "Rob", age: 55}
]);
alert(JSON.stringify(collection));
public unshift(model: Model, options: object): * source
Add a model at the beginning of a collection. Takes the same options as add
.
Return:
* |
public where(attrs: object, first: boolean): * source
Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter.
Return:
* |
Example:
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);
Protected Methods
protected _prepareModel(attrs: object, options: object): * source
Prepare a hash of attributes (or other model) to be added to this collection.
Return:
* |
protected _reset() source
Resets all internal state. Called when the collection is first initialized or reset.