** JSON Data **
{
"data" : [{
"book" : "first book", -- > i want this via model.get('book');
"aurthor" : "xyz"
}
]
}
** Get json data using jquery Ajax. **
var jsonData = {};
$.ajax({
url : 'booklist.json',
async : false,
dataType : 'json',
success : function (json) {
jsonData = json.data;
}
});
** Model declaration here **
var MyModels = Backbone.Model.extend({
initialize : function () {},
defaults : {}
});
var modelinstance = new MyModels(jsonData);
modelinstance.get('book'); // it is giving undefined how can i get this value.
** Please help where i doing wrong.i am new in Backbone. **
If the data is always a single object wrapped up like that then you'd just add a parse
method to your mode:
parse
model.parse(response, options)
parse is called whenever a model's data is returned by the server, in fetch , and save . The function is passed the raw
response
object, and should return the attributes hash to be set on the model.
Something like this:
parse: function(response) {
return response.data[0];
}
You can also trigger a parse
call through the model constructor using the parse: true
option:
constructor / initialize
new Model([attributes], [options])
[...]
If{parse: true}
is passed as an option , the attributes will first be converted by parse before being set on the model.
So if you're manually loading the data through a $.ajax
call then you'd have something like this:
success: function (json) {
var m = new MyModel(json, { parse: true });
// Do something with m...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.