0

** 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. **

1 Answer 1

4

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...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.