Backbone.JS Initialize() collection

The Backbone.JS Initialize() collection method is used to create a model instance.

Syntax:

Backbone.Collection.Initialize ()

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<title>Initialize 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>
<script type="text/javascript">
var X = Backbone.Model.extend({
defaults: {
name: "Tom",
age: 20
},
initialize: function(){
document.write("Hello World");
}
});
var Y = Backbone.Collection.extend({
model: X
});
var student = new X({
name: "Jim",
age: 10
});
var Z = new Y([student]);
document.write("<br>" + JSON.stringify(Z.models));
</script>Hello World<br>[{"name":"Jim","age":10}]
<title>Initialize 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> <script type="text/javascript"> var X = Backbone.Model.extend({ defaults: { name: "Tom", age: 20 }, initialize: function(){ document.write("Hello World"); } }); var Y = Backbone.Collection.extend({ model: X }); var student = new X({ name: "Jim", age: 10 }); var Z = new Y([student]); document.write("<br>" + JSON.stringify(Z.models)); </script>Hello World<br>[{"name":"Jim","age":10}]
  

  
Initialize Collection Example  
  
  
  
  
  
Hello World
[{"name":"Jim","age":10}]

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Hello World
[{"name":"Jim","age":10}]
Hello World [{"name":"Jim","age":10}]
Hello World
[{"name":"Jim","age":10}]

Explanation:
In the above example, the model ‘X’ includes the default values and is extended using the Backbone.Model class. Here, the model instance is invoked by defining the initialize function, and ‘Y’ is a collection instance.