Home Manual Reference Source Repository
import Collection from 'backbone-es6/src/Collection.js'
public class | source

Collection

You can directly use instance of this class. collection

Extends:

Events → Collection

Direct Subclass:

ParseCollection

Indirect Subclass:

TodoList

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:

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(models: Model | Array<Model>, options: object): *

Add a model (or an array of models) to the collection, firing an "add" event for each model, and an "update" event afterwards.

public

at(index: number): *

Get a model from a collection, specified by index.

public

Returns a new instance of the collection with an identical list of models.

public

create(attrs: Model, options: object): *

Convenience to create a new instance of a model within a collection.

public

fetch(options: object): *

Fetch the default set of models for this collection from the server, setting them on the collection when they arrive.

public

findWhere(attrs: object): *

Just like where, but directly returns only the first model in the collection that matches the passed attributes.

public

get(obj: Model): *

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

modelId(attrs: object): *

Override this method to specify the attribute the collection will use to refer to its models in collection.get.

public

parse(resp: object, options: object): object

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.

public

pluck(attr: string): *

Pluck an attribute from each model in the collection.

public

pop(options: object): *

Remove and return the last model from a collection.

public

push(model: Model, options: object): *

Add a model at the end of a collection.

public

remove(models: Model | Array<Model>, options: object): *

Remove a model (or an array of models) from the collection, and return them.

public

reset(models: Array<Model>, options: object): *

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

set(models: Array<Model>, options: object): *

The set method performs a "smart" update of the collection with the passed list of models.

public

shift(options: object): *

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 Array#slice.

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

toJSON(options: object): object

Return an array containing the attributes hash of each model (via toJSON) in the collection.

public

unshift(model: Model, options: object): *

Add a model at the beginning of a collection.

public

where(attrs: object, first: boolean): *

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 on.

public

listenTo(obj: object, name: string, callback: function): Events

Tell an object to listen to a particular event on an other object.

public

listenToOnce(obj: object, name: string, callback: function): Events

Just like listenTo, but causes the bound callback to fire only once before being removed.

public

off(name: string, callback: function, context: object): Events

Remove a previously-bound callback function from an object.

public

on(name: string, callback: function, context: object): *

Bind a callback function to an object.

public

once(name: string, callback: function, context: object): *

Just like on, but causes the bound callback to fire only once before being removed.

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 off.

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#constructor

Params:

NameTypeAttributeDescription
models Array<Model>

An optional array of models to set.

options object

Optional parameters

See:

Public Members

public comparator: string source

A comparator string indicating the attribute to sort.

public length: number source

The length of the models array.

public model: Model source

The default Backbone.Model class to use as a prototype for this collection.

public models: Array<Model> source

An array of models in the collection.

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.

Params:

NameTypeAttributeDescription
models Model | Array<Model>

A single model or an array of models to add.

options object

Optional parameters

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"}
]);

See:

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:

NameTypeAttributeDescription
index number

Index for model to retrieve.

Return:

*

See:

public clone(): Collection source

Returns a new instance of the collection with an identical list of models.

Return:

Collection

Returns a new collection with shared models.

See:

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.

Params:

NameTypeAttributeDescription
attrs Model

Attributes hash for the new model

options object

Optional parameters

Return:

*

Example:

var Library = Backbone.Collection.extend({
    model: Book
});

var nypl = new Library;

var othello = nypl.create({
   title: "Othello",
   author: "William Shakespeare"
});

See:

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:

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

See:

public findWhere(attrs: object): * source

Just like where, but directly returns only the first model in the collection that matches the passed attributes.

Params:

NameTypeAttributeDescription
attrs object

Attribute hash to match.

Return:

*

See:

public get(obj: Model): * source

Get a model from a collection, specified by an id, a cid, or by passing in a model.

Params:

NameTypeAttributeDescription
obj Model

An instance of a model to search for by object, id, or cid.

Return:

*

Example:

var book = library.get(110);

See:

public abstract initialize() source

Initialize is an empty function by default. Override it with your own initialization logic.

See:

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:

NameTypeAttributeDescription
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';
   }
});

See:

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.

Params:

NameTypeAttributeDescription
resp object

Usually a JSON object.

options object

Unused optional parameters.

Return:

object

Pass through to set the attributes hash on the model.

Example:

var Tweets = Backbone.Collection.extend({
   // The Twitter Search API returns tweets under "results".
   parse: function(response) {
      return response.results;
   }
});

See:

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:

NameTypeAttributeDescription
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));

See:

public pop(options: object): * source

Remove and return the last model from a collection. Takes the same options as remove.

Params:

NameTypeAttributeDescription
options object

Optional parameters

Return:

*

See:

public push(model: Model, options: object): * source

Add a model at the end of a collection. Takes the same options as add.

Params:

NameTypeAttributeDescription
model Model

A Model instance

options object

Optional parameters

Return:

*

See:

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.

Params:

NameTypeAttributeDescription
models Model | Array<Model>

An single model or an array of models to remove.

options object

Optional parameters

Return:

*

See:

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:

Params:

NameTypeAttributeDescription
models Array<Model>

An array of models to add silently after resetting.

options object

Optional parameters

Return:

*

Example:

<script>
   var accounts = new Backbone.Collection;
   accounts.reset(<%= @accounts.to_json %>);
</script>

See:

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}.

Params:

NameTypeAttributeDescription
models Array<Model>

An array of models to set.

options object

Optional parameters

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.

See:

public shift(options: object): * source

Remove and return the first model from a collection. Takes the same options as remove.

Params:

NameTypeAttributeDescription
options object

Optional parameters

Return:

*

See:

public slice(): * source

Return a shallow copy of this collection's models, using the same options as native Array#slice.

Return:

*

See:

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:

NameTypeAttributeDescription
options object

Optional parameters

Return:

Collection

See:

public sync(): * source

Uses Backbone.sync to persist the state of a collection to the server. Can be overridden for custom behavior.

Return:

*

See:

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:

NameTypeAttributeDescription
options object

Optional parameters

Return:

object

JSON

Example:

var collection = new Backbone.Collection([
   {name: "Tim", age: 5},
   {name: "Ida", age: 26},
   {name: "Rob", age: 55}
]);

alert(JSON.stringify(collection));

See:

public unshift(model: Model, options: object): * source

Add a model at the beginning of a collection. Takes the same options as add.

Params:

NameTypeAttributeDescription
model Model

A Model instance

options object

Optional parameters

Return:

*

See:

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.

Params:

NameTypeAttributeDescription
attrs object

Attribute hash to match.

first boolean

Retrieve first match or all matches.

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

See:

Protected Methods

protected _prepareModel(attrs: object, options: object): * source

Prepare a hash of attributes (or other model) to be added to this collection.

Params:

NameTypeAttributeDescription
attrs object

Attribute hash

options object

Optional parameters

Return:

*

protected _reset() source

Resets all internal state. Called when the collection is first initialized or reset.