Backbone.js parse Model
Last Updated :
27 Jul, 2022
The Backbone.js parse Model is a function that is called whenever a model’s data is returned by the server. This function is passed with the response object and returns the model’s data. The model has a default implementation of the parse function but we can override this function for flexible usage.
Syntax:
model.parse( response, options );
Parameters:
- response: It is the raw response object which has to parse for data.
- options: This is an object with information about the raw response object.
Example 1: In this example, we will illustrate The Backbonejs parse Model by overriding the default parse function of the model.
HTML
<!DOCTYPE html>
< html >
< head >
< title >BackboneJS parse Model</ title >
< script src =
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 parse Model</ h3 >
< div id = 'hello' ></ div >
< script type = "text/javascript" >
var Person = Backbone.Model.extend({
parse: function (response, options) {
for (var i in response) {
document.getElementById("hello")
.append(`${JSON.stringify(i)} :
${JSON.stringify(response[i])}`);
}
}
});
var person = new Person();
person.fetch();
</ script >
</ body >
</ html >
|
Output:
Backbone.js parse model
Example 2: In this example, we will extract all the emails from the response using the parse function.
HTML
<!DOCTYPE html>
< html >
< head >
< title >BackboneJS parse Model</ title >
< script src =
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 parse Model</ h3 >
< p id = 'hello' ></ p >
< script type = "text/javascript" >
var Person = Backbone.Model.extend({
parse: function (response, options) {
var self = this;
_.each(response, function (data, pos) {
document.write(`${'email' + pos}
: ${data.email} < br >`);
});
}
});
var person = new Person();
person.fetch();
</ script >
</ body >
</ html >
|
Output:
Backbonejs parse Model
Reference: https://backbonejs.org/#Model-parse
Share your thoughts in the comments
Please Login to comment...