Demonstrating Backbone.js: Implement Collections Part 2

Introduction

Welcome to the "Demonstrating Backbone.js" article series. This article demonstrates how to create and use collections in Backbone.js. This article starts with the concept of Backbone.js and various components of it. Previous articles have provided an introduction to views and the implementation of routers. You can get them from the following:

What a Collection is
 
Backbone.js Collections are used to collect groups of Backbone Models into one easily manageable object that can synchronize the data with our server with ease.
 
For example we are doing a Twitter app so models will be each and individual tweet and the collection will be all the tweets combined.
 
Collections in Backbone.js are extended from underscore.js collections. So they have even more methods as I have explained below.
 
Here we have created a model with defaults and we are passing the model to the collection :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScript.JavaScript" %>

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <script src="backbone/Jquery.js" type="text/javascript"></script>

    <script src="backbone/underscore-min.js" type="text/javascript"></script>

    <script src="backbone/backbone-min.js" type="text/javascript"></script>

</head>

<body>

    <script type="text/javascript">

        var Product = Backbone.Model.extend({

            initialize: function () {

                console.log('Product is initialized.');

            },

            defaults: {

                name: 'undefined',

                manufacturer: 'undefined'

            }

        });

        var Items = Backbone.Collection.extend({

            initialize: function () {

                console.log('Items Collection is initialized');

            },

            model: Product

        });

        var product = new Product({ name: "Iphone" });

        var items = new Items(product);

    </script>

</body>

</html>

Collection
 
We can also have multiple models as in the following:
 

items.add([{name:'Ram'},{name:'Sagar'}]);

console.log(items.models);
 
Output

multiple models
 
Summary

In this article, I explained how to use collections in Backbone.js, In future articles we will understand more about Collections with examples.

Previous article:  Demonstrating Backbone.js :Implement Routers Part 1


Similar Articles