Skip to content Skip to sidebar Skip to footer

Backbone Views Not Working With Fetched Json

I'm having issues syncing JSON data received from the server with my views after a fetch. I do not have a collection of 'mainmodel', because I'm only working with one 'mainmodel' a

Solution 1:

You have two problems: one you know about and one you don't.

The problem you know about is that your mainmodel won't automatically convert your v4 JSON to a collection so you end up with an array where you're expecting a collection. You can fix this by adding a parse to your mainmodel:

parse: function(response) {
    if(response.v4)
        response.v4 = newcollection(response.v4);
    return response;
}

The problem you don't know about is that your defaults in mainmodel has a hidden reference sharing problem:

var mainmodel = Backbone.Model.extend({
    defaults: {
        //...
        v4: new collection()
    }
});

Anything you define in the Backbone.Model.extend object ends up on your model's prototype so the entire defaults object is shared by all instances of your model. Also, Backbone will do a shallow copy of defaults into your new models. So if you m1 = new mainmodel() and m2 = new mainmodel(), then m1 and m2 will have exactly the same v4 attribute. You can solve this by using a function for defaults:

var mainmodel = Backbone.Model.extend({
    defaults: function() {
        return {
            v1: '',
            v2: '',
            v3: '',
            v4: newcollection()
        };
    }
});

Post a Comment for "Backbone Views Not Working With Fetched Json"