The Backbone.js clone Collection is a function used to form a new instance of the collection with an identical list of models. This method returns a copy of the collection and initiates a new instance of the collection with its list of models.
Syntax:
collection.clone() ;
Parameters: This method doesn't take any argument.
Example 1: In this example, we will illustrate the Backbone.js clone Collection. We will copy one collection and initiate a new instance.
<!DOCTYPE html>
<html>
<head>
<title>BackboneJS clone collection</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.2.2/backbone-min.js"
type="text/javascript">
</script>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>BackboneJS clone collection</h3>
<script type="text/javascript">
var Book = Backbone.Model.extend();
var b1 = new Book({
title: "Ram",
Author: "Amish Tripathi",
vol: 1
});
var b2 = new Book({
title: "Lolita",
Author: "Vladimir Nabokov",
vol: 2
});
var books = Backbone.Collection.extend({
model: Book,
});
var Library = new books([b1, b2]);
document.write(`Original collection is :
${JSON.stringify(Library)} <br>`);
var temp = Library.clone();
document.write(`Clone collection is :
${JSON.stringify(temp)}`);
</script>
</body>
</html>
Output:
Example 2: In this example, we will clone one collection and see whether methods are copied or not.
<!DOCTYPE html>
<html>
<head>
<title>BackboneJS clone collection</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.2.2/backbone-min.js"
type="text/javascript">
</script>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>BackboneJS clone collection</h3>
<script type="text/javascript">
var Book = Backbone.Model.extend();
var b1 = new Book({
title: "Ram",
Author: "Amish Tripathi",
vol: 1
});
var books = Backbone.Collection.extend({
model: Book,
print: function () {
document.write(JSON.stringify(this), "<br>");
}
});
var Library = new books(b1);
document.write("Print function of original collection : ");
Library.print();
var temp = Library.clone(b1.get('vol'));
document.write("Print function of clone collection : ");
temp.print();
</script>
</body>
</html>
Output:
Reference: https://backbonejs.org/#Collection-clone