The Backbone.js parse Collection is a method that is called by Backbone whenever a Collection’s models are returned by the server. The default implementation simply passes the JSON response. We can override it with a new logic to flexibly parse the response.
Syntax:
collection.parse( response , options );
Parameters:
- response: It is a raw object which contains data regarding the request to the server.
- options: These are the optional parameter regarding the response to the request.
Example 1: In this example, we will illustrate the Backbone.js parse Collection. Here we will parse our Models when we pass them to the collection at the initiation of collection.
HTML
<!DOCTYPE html> < html > < head > < title >BackboneJS parse collection</ title > type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > </ head > < body > < h1 style = "color: green;" > neveropen </ h1 > < h3 >BackboneJS parse collection</ h3 > < script type = "text/javascript" > var Book = Backbone.Model.extend(); var b1 = { title: "Ram", Author: "Amish Tripathi", vol: 1 }; var b2 = { title: "Lolita", Author: "Vladimir Nabokov", vol: 2 }; var b3 = { title: "The Palace of Illusion", Author: "Chitra Banerjee", vol: 1 }; var books = Backbone.Collection.extend({ model: Book, parse: function (response, options) { for (let x of response) document.write(JSON.stringify(x), '< br >'); } }); var Library = new books([b1, b2, b3], { parse: true }); </ script > </ body > </ html > |
Output:
Example 2: In this example, we will parse the data which is coming as a result of the fetch request.
HTML
<!DOCTYPE html> < html > < head > < title >BackboneJS parse collection</ title > type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > < script src = type = "text/javascript" > </ script > </ head > < body > < h1 style = "color: green;" > neveropen </ h1 > < h3 >BackboneJS parse collection</ h3 > < div id = 'para' > </ div > < script type = "text/javascript" > function user_Name(user) { console.log(user.username); } var post = Backbone.Model.extend(); var posts = Backbone.Collection.extend({ model: post, url: "https://...com/users", parse: function (response, options) { _.each(response, user_Name); } }); var comments = new posts(); comments.fetch(); </ script > </ body > </ html > |
Output:
Reference: https://backbonejs.org/#Collection-parse