Backbone.JS Create()

The Backbone.JS Create() collection method creates a new instance of the model in the collection.

Syntax:

Collection.Create ( attribute, options )   

Parameters:
attribute: This parameter is used to specify the attributes of a model in a collection.
options: This parameter is used to specify the parameters like id, name, etc.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<title>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({
sync : function (method, model, options) {
document.write(JSON.stringify(arguments));
}
});
var Y = Backbone.Collection.extend({
model : X
});
var Z = Backbone.View.extend({
initialize : function () {
var values = new Y();
values.create({
name1:"Happy",
name2:"Smiley"
});
}
});
new Z();
</script>{"0":"create","1":{"name1":"Happy","name2":"Smiley"},"2":{"validate":true,"parse":true}}
<title>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({ sync : function (method, model, options) { document.write(JSON.stringify(arguments)); } }); var Y = Backbone.Collection.extend({ model : X }); var Z = Backbone.View.extend({ initialize : function () { var values = new Y(); values.create({ name1:"Happy", name2:"Smiley" }); } }); new Z(); </script>{"0":"create","1":{"name1":"Happy","name2":"Smiley"},"2":{"validate":true,"parse":true}}
  

  
Example  
  
  
  
  
  
{"0":"create","1":{"name1":"Happy","name2":"Smiley"},"2":{"validate":true,"parse":true}}  
  
  

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{"0":"create","1":{"name1":"Happy","name2":"Smiley"},"2":{"validate":true,"parse":true}}
{"0":"create","1":{"name1":"Happy","name2":"Smiley"},"2":{"validate":true,"parse":true}}
{"0":"create","1":{"name1":"Happy","name2":"Smiley"},"2":{"validate":true,"parse":true}}

Explanation:
In the above example, the Create() method creates “values” as an instance of the collection.