CodesJava

Easy learning with example program codes

Backbone.JS At() collection

The Backbone.JS At() collection method retrieves a model from a collection by using a specified index.

Syntax:

index()    

Parameters:
index: This parameter is used to specify the index position for the retrieval of the model from a collection.

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 Student = Backbone.Model.extend({  
defaults: {  
id:"",  
name: ""  
}  });   
var StudentCollection = Backbone.Collection.extend({  
model: Student  
});  
var Student1 = new Student({id:1, name: "Tom" });  
var Student2 = new Student({id:2, name: "Jerry"});  
var X = new StudentCollection();  
X.add([Student1,Student2]);  
document.write('<b>Old Students List:</b> ' + JSON.stringify(X.toJSON()));  
var Student3 = new Student({id:3, name: "Bruno" });    
X.add(Student3,{at:2});   
document.write('<br><b>New Students List:</b> ' + JSON.stringify(X.toJSON()));  
</script>  
</body>  
</html>

Output:

Old Students List: [{"id":1,"name":"Tom"},{"id":2,"name":"Jerry"}]
New Students List: [{"id":1,"name":"Tom"},{"id":2,"name":"Jerry"},{"id":3,"name":"Bruno"}]

Explanation:
In the above example, the model ‘Student3’ is added at 2nd index of the collection.

Please follow and like us:
error









Copyright © 2019 CodesJava DMCA.com Protection Status