0
votes

I am trying to use .json files for mocking the GET requests in backbone collection. Here is my sample file:

[
    {
        "id": '11111',
        "name": "Abdominal Discomfort",
        "favorite": true
    },
    {
        "id": "11110",
        "name": "Abdominal Distension",
        "favorite": true
    },
    {
        "id": "11101",
        "name": "Swollen Abdomen",
        "favorite": true
    },
    {
        "id": "11011",
        "name": "Disorder of Fetal Abdominal Region",
        "favorite": false
    },
    {
        "id": "11100",
        "name": "Dissect of Abdominal Aorta",
        "favorite": false
    },
    {
        "id": "11000",
        "name": "Umbilical Discharge",
        "favorite": false
    }
]

And here is my backbone model/collection entity:

define(['Backbone'], function (Backbone) {
    "use strict";
//MODEL
    var diagnosis = Backbone.Model.extend({});

//COLLECTION
    var c = Backbone.Collection.extend({
        model: diagnosis,
        url:'app-src/js/data-mocks/diagnosis.json'
    });


    return {
        model: diagnosis,
        collection: c
    };

});

And finally i make the fetch call like this in my view:

var that=this;
this.collection.fetch({wait:true,success:function(){
    console.log(that.collection);
}});

In the network console i see the proper 200 status response with a array of objects returned. However the success callback never gets triggered. Further, I have certain .on 'add' events binded and the callbacks for them never gets invoked.

Please suggest where I am going wrong.

1

1 Answers

0
votes

This happened to me a few times, so I decided to make a mini PHP API interface to set the correct Header content-type then serving the JSON file. I'm thinking it's fetching the JSON and jQuery is trying to parse it as XML. So that means you may need to force the request header for 'json'. Try this:

var that=this;
this.collection.fetch({wait:true, dataType: 'json', success:function(){
    console.log(that.collection);
}});