1
votes

Try to use backbone collection to initialize grabbing the json data, but turns out the data is empty. Does backbone collection automatically parse the json data to the model or we have to manually parse it?

 var Book = Backbone.Model.extend({
    title:"",
    isbn:"",
    img:""  
 });

 var Books = Backbone.Collection.extend({
    model:Book,
    url:'latest.json',
    // parse:function(data){
    //  console.log(data);
    // },       
    initialize: function(){
        this.fetch();
    }
 });

Edited to add in my sample json, I validate with jsonlint.com.

[
    {"title":"American Pie","isbn":"345354356","img":"/image/pie.png"},
    {"title":"Long Tails","isbn":"567575576g","img":"/image/long_tails.png"},
    {"title":"Pirates","isbn":"567575765","img":"/image/pirates.png"}
]

Added in JSFiddle link.

http://jsfiddle.net/mochatony/5E3Nc/14/

1
You don't need to manually parse the data if the data if in the correct format. How does your latest.json response look like? - fguillen
Also check in your browser's console to see if the url requested is correct I miss a / in the beginning of this url. - fguillen
@fguillen. Thanks for reply. I check my browser console, and it loads properly. But when I dump the book.toJSON(), it return an [], looks like it did not parse it properly. - TonyTakeshi
Of-topic: beware that the lines as title:"" are not a proper way to initialize default attributes of a Model. Use Model.defaults instead. - fguillen
@fguillen. Thanks for the tips. cheers. - TonyTakeshi

1 Answers

1
votes

You need to make sure these work first

  • No Script errors ( Inspect them in javascript console)

  • Collection.fetch makes a request to correct url ( see resources section in Chrome web inspector)

  • Check that response mime/type is right "application/json" and Server indeed serves JSON string

  • Make sure the JSON response is well formed ( I had this problem . It must be a array and not a object ex : [{},{},{},{}])

  • Lastly refresh from the server ( clear the cache)

Update

Here is a JsFiddle to demonstrate the use http://jsfiddle.net/5E3Nc/16/

note: Parse must explicitly be written only when custom response is sent from server from which you want to build the models collection

by the way, i notices you did this

initialize:function(){
  this.fetch();
}

this won't work. You are expected to use the collection outside of the collection itself for example

var col = Backbone.Collection.extend({url:"data.json"});
var instance = new col({model:Tweet});
instance.fetch();