CodesJava

Easy learning with example program codes

Backbone.JS toJson() collection

The Backbone.JS toJson() collection method is used to get a copy of the attributes of a model using JSON format in the collection.

Syntax:

Collection.toJson (options)      

Parameters:
options: This parameter is used to specify the options as collection instance.

Example:

<!DOCTYPE html> 
<html>
<head>  
<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>  
</head>  
<body>  
<script type="text/javascript">  
var X = Backbone.Model.extend({  
defaults: {  
name: "Tom",  
}  
});  
var XCollection = Backbone.Collection.extend({  
model: X  
});  
$(function(){  
var Z = new XCollection();  
Z.set([{name: 'Jim'},  
{name: 'Minii'},  
{name: 'Tiny'}  
]);   
document.write("Collection:", JSON.stringify(Z.toJSON()));  });  
</script>  
</body>  
</html>  
 
 
<em><strong>Output: </strong></em>
<pre lang="java">
Collection:[{"name":"Jim"},{"name":"Minii"},{"name":"Tiny"}]

Explanation:
In the above example, the model ‘X’ includes the default values and is extended using the Backbone.Model class, ‘XCollection’ is a collection instance and The ‘Z.toJson’ defines the array of toJson inside the collection.

Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status