| title | section | layout |
|---|---|---|
Collections |
collection |
default |
A Collection is a simple wrapper around an Array of Models which provides the following membership events:
- modelAdded - invoked when a model is added to the collection
- modelRemoved - invoked when a model is removed from the collection
- modelChanged - invoked when any property on a model in the collection changes
- updated - invoked when the entire collection has been updated.
To listen to any of these events, use the listen method, e.g.
{% highlight javascript %} var Collection = require('collection').Collection; var Model = require('model').Model; var c = new Collection();
c.listen('modelAdded', function(obj) { console.log('This model was added ', obj.model); });
c.listen('updated', function(obj) { console.log('This collection was updated', obj.collection); });
var m = new Model({name: 'Shane', age: 32}); c.add(m); {% endhighlight %}
While a Collection can be used in a standalone manner for managing and monitoring lists of Models, it's main purpose is to be combined with a CollectionView. Using Collections with a CollectionView, you can simply add and remove models from the Collection, and the view will update it's list of sub views. This decouples data an UI in a very clean manner. See CollectionView for more information on this.