2
votes

I have a backbone collection that I want to fetch and array of models. When I call fetch the ajax request hits the correct rest endpoint. However, the parse function of my collection is never called. I am not sure where the json ends up, but I do get a 200 with a payload back in chrome's network tab. Should I be doing this differently? I have done this in the past (backbone 1.0, on backbone 1.1 now) and it worked fine so I am not sure what the issue is?

 new MonitorCollection(app);
 this.collection.fetch(); // this makes the correct ajax call

Collection:

define([
  'jquery',
  'underscore',
  'backbone',
  'model/monitormodel',
], function ($, _, Backbone, MonitorModel) {    

    var collection = Backbone.Collection.extend({
        initialize: function (app, options) {
            this.app = app;
        },
        url: "api/monitor?since=10",
        model: MonitorModel,

        parse: function (response) {

            console.log(response);
            return response;
        }

    });
    return collection;

});

Model:

define([
  'jquery',
  'underscore',
  'backbone',
  'view/monitordeviceview',
], function ($, _, Backbone, MonitorDeviceView) {

    var model= Backbone.Model.extend({
        initialize: function (app, options) {
            this.app = app;
            this.view = new MonitorDeviceView(this.app);
            this.view.render(this);
        },

        parse: function (response) {

            console.log(response);
            return response;
        }

    });
    return model;

});
1
have you tried to attach a success/error callback to your fetch to see which one is called? also, i think by default, the first parameter for collection initialize, should be an array of models/model attributes. - Yurui Zhang

1 Answers

4
votes

The issue was the json that was getting sent back was not valid json: NaN is not valid in json.

{
        "deviceId": "ac867418c110",
        "totalProbeRequestCount": 0,
        "errorRate": NaN,
        "errorCount": 0,
        "succcesRate": NaN,

To help debug this add error handler and read the links:

These links should help understand how backbone interacts with the sever.

    var collection = Backbone.Collection.extend({
        initialize: function (options) {
            this.on("error", this.error, this)
            this.fetch();
        },
        url: "api/monitor?since=10",
        model: MonitorModel,

        parse: function (data) {
            console.log(data);
            return data.items;
        },

        error: function (model, response, options) {
            console.log(model);
            console.log(response);
            console.log(options);
        }

    });