Module: UWA/Class/Collection

UWA/Class/Collection

A logical ordered grouping of instances of UWA.Class.Model with methods and properties for working with (grouping, sorting, filtering, etc) these groups of models.

Events triggered by instances of UWA.Class.Collection:

Any event that is triggered by an instance of UWA.Class.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, you can listen to "onChange" events fired by the collection to be notified when any model in the collection has been modified :

documents.addEvent("onChange:selected", ...)

Now here are the events that are specific to instances of UWA.Class.Collection :

Event name Arguments passed to callback Description
'onAdd' model, collection, options This event is fired when a model is added to a collection.
'onRemove' model, collection, options This event is fired when a model is removed from a collection. The model's index before removal is available as options.index
'onReset' collection, options This event is fired when the collection's entire contents have been replaced. For convenience, the list of any previous models is available as options.previousModels
'onSort' collection, options This event is fired when the collection has been re-sorted.
'onAnyEvent' event name, event data... This event is fired for any other triggered event, passing the event name as the first argument.

Define your own custom collection by sub-classing UWA.Class.Collection:

Just like UWA.Class.Model and {@link module:UWA/Class/View.UWA.Class.View|UWA.Class.View}, a UWA.Class.Collection can be extended (i.e. sub-classed) using UWA.Class.extend mechanism and defining an setup function when extending will be invoked when a collection is created.

The methods you have to (or that you should) override when defining your custom collection are the following :

  • {@link module:UWA/Class/Collection.UWA.Class.Collection#setup|setup} method, to initialize a newly created instance of collection.
  • sync method, to retrieve a data collection from the backend.
  • parse method, to transform the backend response into an array of models.
  • model property, to specify the model class the collection contains.
  • comparator property, to maintain the collection in order.

By extending/subclassing UWA.Class.Collection, you can define your own business logic on top of UWA.Class.Collection, see an advanced example below that will show you the benefits of defining your custom collections for your business logic.

Mutator methods that will modify the contents of the collection

These are the methods that allows you to :

  • add models to the collection (add, {@link module:UWA/Class/Collection.UWA.Class.Collection#push|push}, unshift),
  • remove models from the collection (remove, {@link module:UWA/Class/Collection.UWA.Class.Collection#pop|pop}, shift),
  • force the re-sorting of the collection (sort),
  • smartly update or replace the contents of the collection (set, {@link module:UWA/Class/Collection.UWA.Class.Collection#reset|reset}).

Accessor methods that do not modify the collection but return some representation of the collection

  • get gets a model from the collection.
  • at returns a model from a collection, given a position.
  • first returns the first model of the collection.
  • last returns the last model of the collection.
  • toArray returns a shallow copy of all the models in the collection, as an array.
  • slice returns a portion of the collection as an array of models.
  • rest returns all but the N first models in the collection.
  • initial returns all but the N last models in the collection.
  • without returns a copy of the collection with all of the passed instances of models removed.
  • indexOf returns the first index at which a given model can be found in the collection.
  • lastIndexOf returns the last index at which a model can be found.
  • contains returns true if the model is present in the collection.
  • size returns the number of models in the collection.
  • isEmpty returns true if the collection contains no model.
  • toJSON returns an array containing the attributes hash of each model in the collection.
  • pluck plucks an attribute from each model in the collection.
  • shuffle returns a shuffled copy of the collection models as an array.
  • where returns an array of all the models in the collection that match the passed attributes.
  • findWhere returns the first model in the collection that matches the passed attributes.
  • invoke invokes a provided model method name once per model of the collection.

Iteration methods taking as arguments functions to be called back when processing the collection

  • forEach executes a provided function once per model of the collection.
  • map returns a new array with the results of calling a provided function on every model.
  • every tests whether all models in the collection pass the test implemented by the provided function.
  • some tests whether some model in the collection passes the test implemented by the provided function.
  • sortBy returns a sorted copy of the collection’s models.
  • groupBy splits the collection into sets.
  • countBy sorts the collection into groups and returns a count of models in each group
  • find returns the first model in the collection for which the provided filtering function ‘filter’ returns true.
  • filter creates a new array with all the models of this collection for which the provided filtering function ‘filter’ returns true.
  • reject returns the models in this collection without the models that the truth test (filter) passes.
  • reduce applies a function against an accumulator and each model to reduce the collection to a single value.
  • reduceRight, the right-associative version of reduce.
  • max returns the maximum model in the collection, with regards to a criterion.
  • min returns the minimum model in the collection, with regards to a criterion.

Methods performing C/R/U/D operations in the backend

  • fetch fetches the default set of models for this collection from the backend.
  • create create a new instance of a model within the collection.

Example

// This example is a brief overview of some of the methods/APIs offered
// by UWA.Class.Collection. Have a look at the detailed documentation of each API
// if needed.

// Given this model definition :
var Post = UWA.Class.Model.extend({});
// Let's define a collection Posts of Post models :
var Posts = UWA.Class.Collection.extend({
    url: "/blogposts",
    model: Post // the type of models inside the collection
});
// An url has been set for this collection, it will be used when requests will
// be made to the backend.
// Let's instanciate a new collection :
var postsList = new Posts();
// And 3 new Post models :
var post1 = new Post({
    title: "Post1 title",
    message: "message 1"
});
var post2 = new Post({
    title: "Post2 title",
    message: "message 2"
});
var post3 = new Post({
    title: "Post3 title",
    message: "message 3"
});
// Now these models can be added this way to the collection :
postsList.add(post1);
// Or this way :
postsList.add([post2, post3]);
// Models can be directly created in the collection this way :
postsList.add(new Post({
    title: "Post4 title",
    message: "message 4"
}));
// ... or this way :
postsList.add({
    title: "Post5 title",
    message: "message 5"
});
// Now, to get the array of the models in the collection :
var posts = postsList.toArray();
// Models and their attributes can be accessed this way :
postsList.at(0).get("title"); // at() returns the post in the collection at the
                              // given position 0. Note that collections are
                              // 0-based.
// or this way :
postsList.get("3chk57hl").get("title");
// ... if there is a model identified with the id "3chk57hl"
// Collections have a forEach() method allowing to execute a provided function
// once per model in the collection. For example, to display the title of each
// Post in the collection :
postsList.forEach(function (post) {
    UWA.log(post.get("title"));
});
// This could also be coded this way :
postsList.pluck("title").forEach(function (title) {
    UWA.log(title);
});
// The method filter() allows to return an array of all models that pass a given
// criterion. Let's get the list of Posts which title's number is above 3 :
var somePosts = postsList.filter(function (post) {
    return parseInt(post.get("title")[4], 10) > 3;
});
// find() works just like filter() but returns the first model satisfying the criterion.
// Let's fetch data from the backend (after a reset to empty it) :
postsList.fetch({
    reset: true,
    onComplete: function (posts, response, options) {
        posts.pluck("title").forEach(function (title) {
            UWA.log(title);
        });
    },
    onFailure: function (posts, response, options) {
        UWA.log("Oupss");
    }
});
// Just like models, collections emit events that can be listened to.
// To get notified of any attribute change of any post in the collection :
postsList.addEvent('onChange', function (post) {
    UWA.log(UWA.String.format("{0} changed !", post.get("title")));
});
// The complete list of events emitted by collections can be found above.
// Once again, this example is a brief overview of some of the methods/APIs offered
// by UWA.Class.Collection. Have a look at the detailed documentation of each API.

Classes

UWA.Class.Collection