Collections in backbone js - Learning Backbone js
This entry is part 8 of 14 in the series for A Complete Guide for Learning Backbone Js
- Introduction and Installation
- Representing your data in javascript
- Defining Models in backbone js
- Adding Validations in models backbone js
- Explaining views in backbone js
- How to use templates in backbone js
- How to improve templates in backbone js
- Collections in backbone js
- Collection views in backbone js
- Template helpers in backbone js
- How to use namespace in backbone js
- How to handle dom events in backbone js and define your custom events (Live Demo)
- Routing in backbone js
Agenda
So from previous lessons, we know how to create a Person model, We are aware how to create PersonView and us how to define inline and external templates. In this lesson, we will learn collections in backbone js and in the lesson we will learn how to define views for collections in backbone js.
What we have till now
So here is the code that we have from the previous lesson.
Defining a collection
Now from above code if we want to create a new person and add that model in view that it will become messy and it will go so much messy if we have to define some ten people records. Thanks to the backbone that we have collections in backbone js. So here is how we define collections in backbone js.
Setting up the defaults
So we tell collection that what kind of objects we are dealing with by specifying the model attribute. In this case, we have PeopleCollection, so we have Person defined there. So let’s see how to can use it. So we have:
Fire up the console and fire these commands
Output on Chrome Console
Lets see what we have on console.
Another way of adding data to collection
Another way to adding data to collections is:
So you can loop over it. Do so many things as collections have so much data stored in it on model objects. It may seem like we can store in the form of the array but collections have their collections view, and that makes them pretty powerful. Let’s talk about collection views in next lesson, and that will help you to understand the importance of collections.
Source code
If you are facing any issues. Check out the source code files at github. I will be creating more and more directories in the same repo regarding each post. Still, if you have any doubts you can comment on the blog post itself, and I will try to reply back asap.