BackboneJS - Collection Unshift



Description

It is used to add the specified model at the beginning of a collection.

Syntax

collection.unshift(models, options)

Parameters

  • models − It contains the names of the collection instances, which is to be added at the beginning of a collection.

  • options − It includes the model types and adds them to the collection instance.

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Collection Example</title>
      <script src="/?originalUrl=https%3A%2F%2Fcode.jquery.com%2Fjquery-2.1.3.min.js"
         type = "text/javascript"></script>
      
      <script src="/?originalUrl=https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Funderscore.js%2F1.8.2%2Funderscore-min.js"
         type = "text/javascript"></script>
      
      <script src="/?originalUrl=https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fbackbone.js%2F1.1.2%2Fbackbone-min.js"
         type = "text/javascript"></script>
   </head>
   
   <body>
      <script type = "text/javascript">
      
         //'Player' is a model and contains defualt values for the model
         var Player = Backbone.Model.extend ({
            defaults: {
               name: 'sachin',
               country: 'india'
            }
         });

         //'Players' is an instance of the collection
         var Players = Backbone.Collection.extend ({
            model: Player  //model 'Player' is specified by using model property
         });

         //Here, instantiating models along with "new" keyword and store them in the collection instance
         var player1 = new Player({ id: 1, name: 'gayle', country: 'west indies'});
         var player2 = new Player({ id: 2, name: 'yuvraj', country: 'india'});
         var teamArray = [player1, player2];

         //The unshift() method adds the 'player2' model to the beginning of the collection
         teamArray.unshift(player2);

         //Instantiate new collection by passing in an array of models
         var players = new Players(teamArray);
         document.write(JSON.stringify(players));
      </script>
   </body>
   
</html>

Output

Let us carry out the following steps to see how the above code works −

  • Save the above code in the unshift.htm file.

  • Open this HTML file in a browser.

backbonejs_collection.htm
Advertisements