Reputation: 13239
i'm a beginner to backbone.js
why would you want to use a COLLECTION?
Can't you just have a view associated with each model?
Also, does an event bond to a collection of model apply to all models?
Upvotes: 0
Views: 750
Reputation: 13105
When you are operating on large datasets it is very much necessary to have a mechanism to perform operations on whole datasets or subsets. In Backbone.js Collection class provides this mechanism. A few very frequent usages of Collection may be outlined as follows :
Suppose you are fetching the results of a query from a database. Now you can create a model corresponding to the structure of record, define a collection, create a collection instance, define the url (and if required customize the ajax request) and then give a call to fetch. This is more advantageous to having an array of models : firstly it is more convenient than to iterate through the parsed json data structure and create a model from each record object. Secondly the entire collection can be updated at once to the server. As pointed out by Mario, it makes working with related records very convenient.
Secondly, Collection class provides you a base class which you can easily auxiliate with your functions to provide custom filtering and sorting capabilities.
You can have Views eg. data grids, trees etc to represent the collection. It is convenient to code and also think in terms of a view representing a collection.
Upvotes: 2
Reputation: 6790
You could use a collection is to represent a one-to-many relationship. This is type of thing is perfect when your backend datastore is a document database (having embedded documents).
You can also use a collection to allow for iteration over your models.
Since a model can only belong to a single collection it almost makes sense at times to treat a collection like a table in the database. In the database I have a people table. In my javascript I have a people collection.
(The reason a model can only belong to a single collection is that upon adding a model to a collection the collection stores a reference to itself directly on the model. Adding a model to a second collection would overwrite the model's reference to the first collection.)
Upvotes: 1
Reputation: 2837
You use them when you have nested models, see http://documentcloud.github.com/backbone/#FAQ-nested
I guess you could have a view associated with each model but not necessarily. Not sure about the last part, maybe run a quick test.
Upvotes: 1