CodesJava

Easy learning with example program codes

Backbone.JS Sort() collection


The Backbone.JS Sort() collection method is used to sort the items in the collection.

Syntax:

Collection.Sort (options)

Parameters:
options: This parameter is used to specify either of the two values: “true” or “false”. True enables the sorting while false disables it.

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();  
var S_name = [  
{id:10, name: 'Tom'},  
{id:2, name: 'Jim'},  
{id:33, name: 'Kim'}  
];  
var Y = new Backbone.Collection(S_name,{  
model:X,  
comparator: 'id'   
});  
document.write("Sorted based on id: ",  
JSON.stringify(Y)  );  
</script>  
</body>  
</html>

Output:

Sorted based on id: [{"id":2,"name":"Jim"},{"id":10,"name":"Tom"},{"id":33,"name":"Kim"}]

Explanation:
In the above example, the Sort() method maintains the collection in sorted order based on the value of the ‘id’.

Please follow and like us:


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki