Backbone.js get Collection
Last Updated :
12 Dec, 2022
The Backbone.js get Collection is used to retrieve model from a Collection. This method uses unique identified to get the model we can use user define id value or by default cid value or model name.
Syntax:
collection.get ( id );
Parameters:
- id: It is a unique identifier that is used to identify the model in the collection.
Example 1: In this example, we will illustrate the Backbone.js get Collection. We will use default cid as a unique identifier in this example.
HTML
<!DOCTYPE html>
< html >
< head >
< title >BackboneJS get collection</ title >
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
</ head >
< body >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< h3 >BackboneJS get collection</ h3 >
< script type = "text/javascript" >
var Book = Backbone.Model.extend();
var books = Backbone.Collection.extend({
model: Book,
});
var Library = new books();
var b1 = new Book({
title: "Ram",
Author: "Amish Tripathi"
});
var b2 = new Book({
title: "Lolita",
Author: "Vladimir Nabokov"
});
Library.add(b1);
Library.add(b2);
document.write("Author Name of first Book is : ",
Library.get('c1').get('Author'), '< br >');
document.write("Author Name of second Book is : ",
Library.get('c2').get('Author'));
</ script >
</ body >
</ html >
|
Output:
Backbone.js get Collection
Example 2: In this example, we will make our own unique identifier with the help of modeled models and use it as a unique identifier to get the model.
HTML
<!DOCTYPE html>
< html >
< head >
< title >BackboneJS modelId collection</ title >
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
< script src =
type = "text/javascript" >
</ script >
</ head >
< body >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< h3 >BackboneJS modelId collection</ h3 >
< script type = "text/javascript" >
var Book = Backbone.Model.extend();
var books = Backbone.Collection.extend({
model: Book,
modelId: function (attr, o) {
return attr.title + attr.vol;
}
});
var Library = new books();
var b1 = new Book({
title: "Ram",
Author: "Amish Tripathi",
vol: 1
});
var b2 = new Book({
title: "Beloved",
Author: "Toni Morrison",
vol: 1
});
Library.add(b1);
Library.add(b2);
document.write("Author Name of first Book is : ",
Library.get('Ram1').get('Author'), '< br >');
document.write("Author Name of second Book is : ",
Library.get('Beloved1').get('Author'));
</ script >
</ body >
</ html >
|
Output:
Backbone.js set Collection
Reference: https://backbonejs.org/#Collection-get
Share your thoughts in the comments
Please Login to comment...