1
votes

I'm creating a collection in backbone js, after this fetch data from the backend, I print in the console inspector in chrome, but something caught my attention in the attributes.

The collection has models, and inside of each model has an attribute called "collections" and inside of this has a attribute call "models" and so on

I'm not interacting yet with the views, only create a collection and fetch de data.

This is what happens in the console:

Screenshot

This is the code that I'm using for the parse:

var TablesCollections = Backbone.Collection.extend({
    model: Table,
    url: '/api/tables',
    parse: function(response) {
        if(response.procced == 7) {
            return response.data;
        } else {
            return "An error has trigger";
        }
    },
    initialize: function() {
        this.fetch();
    }
});

And this is the models:

var Table = Backbone.Model.extend({
    defaults: {
        'title': '',
        'titlestring' : '',
        'schema': {},
        'manageschema': {},
    },
    parse: function(response){

        if(response.proceed){
            if(response.proceed == 4){
                response.data.schema = JSON.parse(response.data.schema);
                response.data.manageschema = JSON.parse(response.data.manageschema);
                response = response.data;
            }
        } else {
            if(response.schema != 'Na'){
                response.schema = JSON.parse(response.schema);    
            }
            if(response.manageschema != 'Na'){
                response.manageschema = JSON.parse(response.manageschema);    
            }    
        }
        return response;
    },
});

Why is there multiple copies of the collection nested inside the models?

1

1 Answers

2
votes

This is normal. Each Backbone Model that is added to a collection has a reference to the collection that it belongs to. (accessed via this.collection where this is the model)

What you see in the console is a circular reference. The collection has models. Each model has a reference to the collection. That same collection has the same models which have the same reference to the collection, etc...

Model's constructor documentation:

The model.collection property is normally created automatically when you first add a model to a collection.

In your screenshot, you can see that cid: "c8". This is the client id which Backbone adds to models and collections. This shows you that it's the same model reference each time.

enter image description here