BackboneJS - SPLessons

Backbone.js Collection

Home > Lesson > Chapter 5
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Backbone.js Collection

Backbone.js Collection

shape Introduction

This chapter demonstrates about the Backbone.js Collection is used to contact with some group of related models which handles loadings & savings following are the concepts covered in this chapter.
  • Collection

Collection

shape Description

A collection is an ordered set of a model is used to contact with some group of connected models and which handles the loading & saving of some different models to the server. Backbone.js provides a helper functions is used to perform aggregation and computation against a list of models. A user can produce own collection by extending the backbone's collection class. If an event is triggered on collection model then which may even be triggered on the collection directly. It facilitates to pay an attention for changes to a particular attributes in any model in a collection. The table below demonstrates the list of methods which are used to manipulate the backbone.js collection.
method Description
extend Which is used to extends backbone.collection class to create an own collection.
get Which is used to retrieve the model from a collection by using id.
set Which used to update the collection with a set of items in a model while updating if any new model found then it will be added to the model.
models Which specify the model class in which user need to override the model property of the collection class.
add Is used to add a model or some array of models to the collection.
reset Is used to empty the entire collection and resets the collection and populate with a new array of models.
remove Is used to removes a single model or array of a models from the collections.
at Is used to get the model from the collection by specified index.
push Which takes an array of models and push the models to the collection and which is just similar to the add() method.
pop Which takes an array of models and remove the models from the collection and which is just similar to the add() method.
shift Is used to remove the first item from the collection.
Unshift Is used to add specified model at the beginning of the collection.
shift Is used to remove the first item with the collection.
sync Which is used to display the state of the collection by using Backbone.sync method.
sort Which is used to sort the items in the collection.
length Which is used to count a number of models in the collection.
slice Which is used to display the shallow copy of the element from the collection.
pluck Which is used to retrieve the attributes from the model in the collection.
where Which is display the model by using the matching attribute in the collection
clone Which is used to return the shallow copy of the specified object?
url Which is used as an instance of the model and returns URL where the model resource is located.
fetech By using Sync method user can extract the data in the collection.
create Which creates the new instance of the model in the collection.
By using Extend method user can extend the Backbone.js class to create own collections which provide some instance properties and optional class properties attached directly to the constructor function The syntax below demonstrates the extend(). [code] Backbone.Collection.extend(properties, classProperties) [/code] Parameters The code below demonstrates the extend() as shown below. [html] <!DOCTYPE html> <head> <title>Extend Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //The model 'MySite' includes default values and extended using the Backbone.Model class var MySite = Backbone.Model.extend({ defaults: { Sites: "SPLESSONS", language: "Java" }, }); //'MySite1' is an instance of the collection var MySite1 = Backbone.Collection.extend({ model: MySite }); //The collection 'MySite1' is instantiated by using new keyword var myval=new MySite1({}); //The JSON.stringify() method returns values of collection in the JSON format document.write("The values in the collection are: ",JSON.stringify(myval)); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
get() method is used to retreive a model from the collection like by an id or cid which are done by passing in a model and the syntax below demonstrates the get(). [code] collection.get(id) [/code] Parameters The code below demonstrates the get() as shown below. [html] <!DOCTYPE html> <head> <title>Get Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> var MyCollection = new Backbone.Collection(); //The on() method binds callback function to 'MyCollection' instance and invokes whenever an event triggers MyCollection.on("change:title", function(model) { //When event triggers, it retrieves the title from the collection document.write("SPlessons-- " + model.get('title')); }); MyCollection.add({id: 2}); //The 'myvalues' object gets the 'MyCollection' with id = 2 var myvalues = MyCollection.get(2); //Sets the value for the title myvalues.set('title', 'A Solution of All Technology.'); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
set method is used to update the collections with a set of items in the model. If a model is in the list but which is not available in the collection then those are added and if the model is already present in the collection then the attributes will be merged the syntax of the set as shown below. [code] collection.set(models,options) [/code] Parameters The code below demonstrates the set() as shown below. [html] <!DOCTYPE html> <head> <title>Set Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //Here the model name is 'Site' and contains default value var Site = Backbone.Model.extend({ defaults: { name: 'Java' }, }); //'SitesCollection' is an instance of collection var SitesCollection = Backbone.Collection.extend({ model: Site }); var site1 = new Site({ name: "C Programing" });//'site1' is instance of the mode var mycollection = new SitesCollection();/'mycollection' is instance of the collection mycollection.add(site1); //adding model instance 'site1' along with value to the collection //The set() method update the 'site1' model by passing this value in the collection mycollection.set([site1, { name: ".Net" }]); document.write(JSON.stringify(mycollection.toJSON())); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
Which specify the array or models which are created inside of a collection. The syntax below demonstrates the models(). [code] collection.models [/code] The code below demonstrates the models() as shown below. [html] <!DOCTYPE html> <head> <title>Models Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //The model 'MySite' contains default values and extended using the Backbone.Model class var MySite = Backbone.Model.extend({ defaults: { Sites: "Java", Name: "SPlessons" } }); //The 'MySite1' is a collection instance and model 'MySite' is specified by overriding the 'model' property var MySite1 = Backbone.Collection.extend({ model: MySite }); var site1 = new MySite({ Sites: "C", Name: "SPlessons" }); var site2 = new MySite({ Sites: ".Net", Name: "SPlessons" }); //Passing the objects 'site1' and 'site2' to the collection var myval=new MySite1([site1,site2]); //The 'myval.models' define the array of models inside the collection document.write("The values of models in the collection are: "+JSON.stringify(myval.models)); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
Add method is used to add a single model or array of models to the collection. [code] collection.add(models,options) [/code] Parameters The code below demonstrates the add() as shown below. [html] <!DOCTYPE html> <head> <title>Add Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //Consider a model 'Site' containing default values. var Site = Backbone.Model.extend({ defaults: { Sites: "Java", Name: "SPlessons" } }); //The 'SitesCollection' is a collection instance and model 'Player' is specified by overriding the 'model' property var SitesCollection = Backbone.Collection.extend({ model: Site }); //The instances "site1" and "site2" are created for the model "site1" var site1 = new Site ({Site: "C", Name:"India"}); var site2 = new Site({Site: "CPP", Name:"India"}); var site3 = new Site({Site: ".Net", Name:"India"}); //The add() method adds the models 'site1''site2' and'site3' to the collection instance 'mycollection' var mycollection = new SitesCollection(); mycollection.add([site1,site2,site3]); //The 'length' property deteremines length of the collection document.write('Number of added Site : ' + mycollection.length); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
The Backbone.js collection reset is employed to exchange a collection with another list of models. It updates the collection in bulk. It will reset {the collection|the gathering} with a new list of models or can empty the complete collection. Which is completely different from adding and removing collection as a result of they're good to vary one at a time. On the opposite hand, Reset collection makes changes in bulk. [code] collection.reset(models,options) [/code] Parameters The code below demonstrates the reset() as shown below. [html] <!DOCTYPE html> <head> <title>Reset Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //The 'T_Name' is a model name and includes default value var T_Name = Backbone.Model.extend({ defaults: { site: "India" } }); //'NamesCollection' is an instance of collection and model 'T_Name' is specified by using model property var NamesCollection = Backbone.Collection.extend({ model: T_Name }); //The 'site1' and 'site2' are the instances of the model 'T_name' var site1 = new T_Name({site: "SPlessons"}); var site2 = new T_Name({site: "Simple Programming"}); //Add the model instances to the collection using 'mycollection' collection instance var mycollection = new NamesCollection(); mycollection.add([site1,site2]); //The 'length' property defines length of the collection document.write('Number of added sites: ' + mycollection.length); document.write("<br>"); //Here, the reset() method resets the collection otherwise empties the collection mycollection.reset(); document.write('Number of sites after reset: ' + mycollection.length); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
Remove method is used to remove a single model or array of models from the collection. [code] ollection.remove(models,options) [/code] Parameters The code below demonstrates the remove() as shown below. [html] <!DOCTYPE html> <head> <title>Remove Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //'Site' is a model and contain defualt value for model var Site = Backbone.Model.extend({ defaults: { sitel: ".Net", name:"SPLessons" } }); //The 'SitesCollection' is a collection instance and model 'Site' is specified by overriding the 'model' property var SitesCollection = Backbone.Collection.extend({ model: Site }); //The instances "site1" and "site1" are created for the model "Player" var site1 = new Player({site: "C", name:"SPlessons"}); var site2 = new Player({site: "Java", name:"Simple Programing"}); //The add() method adds the models 'site1' and 'site2' to the collection instance 'mycollection' var mycollection = new SitesCollection(); mycollection.add([site1,site2]); //The 'length' property deteremines length of the collection document.write('Number of added sites : ' + mycollection.length); document.write("<br>"); //The remove() method removes the 'site1' model from the collection mycollection.remove([site1]); document.write('Number of removed sites : ' + mycollection.length); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
At method is used to retrive a model from collection by using the specified index the syntax below demonstrates the at(). [code] index() [/code] Parameters The code below demonstrates the at() as shown below. [html] <!DOCTYPE html> <head> <title>At Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //The model name is 'Site' and contains default values var Site = Backbone.Model.extend({ defaults: { id:"", name: "" } }); //'SitesCollection' is an instance of the collection var SitesCollection = Backbone.Collection.extend({ model: Site //model 'Site' is specified by using model property }); var site1 = new Site({id:1, name: "C" }); var site2 = new Site({id:2, name: "Java"}); //The add() method adds the models 'Site1' and 'Site2' to the collection instance 'mycollection' var mycollection = new SitesCollection(); mycollection.add([site1,site2]); document.write('<b>Sites added are :</b> ' + JSON.stringify(mycollection.toJSON())); var site3 = new Site({id:3, name: ".Net" }); //Here, adding the model 'site3' at 0th index of the collection mycollection.add(site3,{at:0}); //display all the models added. site3 will be added at the 0th position document.write('<br><b>Now the new list of players is :</b> ' + JSON.stringify(mycollection.toJSON())); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
push method is similar to the add () method which adds model at the end of a collections the syntax below demonstrates the push(). [code] collection.push(models, options) [/code] Parameters The code below demonstrates the push() as shown below. [html] <!DOCTYPE html> <head> <title>Push Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //The 'Site' is a model name and includes the default values var Site = Backbone.Model.extend({ defaults: { c_id:"", site: "" } }); //The 'SitesCollection' is a collection instance and model 'Player' is specified by using model property var SitesCollection = Backbone.Collection.extend({ model: Site }); //The 'site1', 'site2' and 'site3' are instances of the model 'Player' var site1 = new Site({c_id:1, site: "Australia" }); var site2 = new Site({c_id:2, site: "Canada"}); var site3 = new Site({c_id:3, site: "India"}); var mycollection = new SitesCollection(); //Here, the push() method adds the above models to the collection mycollection.push(site1); mycollection.push(site2); mycollection.push(site3); //'length' property defines total number of models in the collection document.write('Number of site added: ' + mycollection.length); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
pop method is just similar to the remove() method which takes an array of models and removes from the collection the syntax below demonstrates the pop(). [code] collection.pop(models, options) [/code] Parameters The code below demonstrates the pop() as shown below. [html] <!DOCTYPE html> <head> <title>Pop Collection Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> </head> <body> <script type="text/javascript"> //The 'Site' is a model name and includes the default values var Site = Backbone.Model.extend({ defaults: { c_id:"", site: "" } }); //The 'SitesCollection' is a collection instance and model 'Player' is specified by using model property var SitesCollection = Backbone.Collection.extend({ model: Site }); //The 'site1', 'site2' and 'site3' are instances of the model 'Player' var site1 = new Site({c_id:1, site: "C" }); var site2 = new Site({c_id:2, site: "Java"}); var site3 = new Site({c_id:3, site: ".Net"}); var mycollection = new SitesCollection(); //Here, the push() method adds the above models to the collection mycollection.push(site1); mycollection.push(site2); mycollection.push(site3); document.write('Number of pushed site : ' + mycollection.length); document.write("<br>"); //The pop() method removes the models from the collection mycollection.pop(site1); document.write('Number of popped site : ' + mycollection.length); </script> </body> </html> [/html] Result By running the above code in a preferred browser user can get the following output as shown in below image.
Underscore Methods The table below demonstrates the underscore.js methods which provides the functionality used on the Backbone.Collection.
method Description
_.each(list, iterate, [context]) By using the iterate function user can iterate each nd every element in the collection.
_.map(list, iterate, [context]) By using iterate function user can map each value and displays them in a new array.
_.reduce(list, iterate, memo, [context]) Which is also known as injecting and fold is used to reduce the list of values to a single value.
_.find(list, predicate, [context]) Which find each and every value and returns the first one which process predicate or test.
_.filter(list, predicate, [context]) Which filter each and every value and returns the array of values which process predicate or test.
_.reject(list, predicate, [context]) Which returns the rejected elements in the list which don't pass the predicted values.
_.every(list, predicate, [context]) If elements in the list pass the predicted values which return.
_.some(list, predicate, [context]) If elements in the list pass the predicted values which returns.
_.contains(list, value, [fromindex]) If value present in the list which returns true.
_.invoke(list, method name, *arguments) Which invokes the method name using method name() on each value in the list.
_.max(list, [iterate], [context]) Is used to to specify the maximum value in the list.
_.min(list, [iterate], [context]) Is used to specify the minimum value in the list.
_.sortby(list, [iterate], [context]) Is used to return the sorted elements in ascending order by using the iterate in the list.
_.groupby(list, [iterate], [context]) Which divides the collection values into sets and grouped by using iterated in the list.
_.shuffle(list) Which return the shuffled list.
_.size(list) Which define number values in the list.
_.toarray(list) Which defines an array of the list.
_.first(array, [n]) Which specify the first element of the array in the list.
_.initial(array, [n]) Which specify the last entry of the array in the list and it returns everything.
_.last(array, [n]) Which specify the last element of the array in the list.
_.last(object) which returns there are no objects in the list.
_.chain(obj) which is used to return wrapped object.

Summary

shape Key Points

  • A collection is set of models.
  • User can create own collections by extending Backbone.js class.
  • Collection can deal with the group of related models.