In this article, we will discuss Backbone.js length collection. The Backbone.js length collection is used to return the total number of elements/values present in the model collection.
Syntax:
Backbone.Collection.length
Parameters: It takes no parameters.
Example 1: In this example, we will create a model array with one element and return the length.
HTML
<!DOCTYPE html> < html > < head > < script type = "text/javascript" src = </ script > < script type = "text/javascript" src = </ script > < script type = "text/javascript" src = </ script > </ head > < body > < script type = "text/javascript" > var data = Backbone.Model.extend({ defaults: { id: "1", name: "sravan kumar gottumukkala", age: "67" }, }); var data1 = Backbone.Collection.extend({ model: data }); var final = new data1({}); document.write( "Values:", JSON.stringify(final.toJSON()) ); document.write("< br >"); document.write("Length:", final.length); </ script > </ body > </ html > |
Output:
Values:[{"id":"1","name":"sravan kumar gottumukkala","age":"67"}] Length:1
Example 2: In this example, we will create a model array with four elements and return the length.
HTML
<!DOCTYPE html> < html > < head > < script type = "text/javascript" src = </ script > < script type = "text/javascript" src = </ script > < script type = "text/javascript" src = </ script > </ head > < body > < script type = "text/javascript" > var datas = Backbone.Model.extend({ defaults: { name: "sravan" } }); var datacollection = Backbone.Collection.extend({ model: datas }); var data1 = new datas({ name: "ram" }); var data2 = new datas({ name: "shivam" }); var data3 = new datas({ name: "ramya" }); var data4 = new datas({ name: "deepu" }); var final = new datacollection(); final.add([data1, data2, data3, data4]); document.write( "Values:", JSON.stringify(final.toJSON()) ); document.write("< br >"); document.write("Length:", final.length); </ script > </ body > </ html > |
Output:
Values:[{"name":"ram"},{"name":"shivam"},{"name":"ramya"},{"name":"deepu"}] Length:4
Reference: https://backbonejs.org/#Collection-length