Captain Obvious
Captain Obvious

Reputation: 785

Circular reference backbone models + require.js

i'm trying to create a Tree with backbone.js models, but i'm having a problem with it:

Collection: MCollection:

define
(
    ['backbone', 'models/M'],
    function(Backbone, M)
    {
        'use strict';        

        return Backbone.Collection.extend
        (
            {
                model: M,
                }
            }
        );
    }
);

and the model that has a collection that depends on that model...

Model: M

define
(
    ['backbone', 'underscore', 'vent', 'collections/MCollection'],
    function(Backbone, _, vent, MCollection)
    {
        'use strict';

        return Backbone.Model.extend
        (
            {               
                _children : null,


                initialize : function(attributes, options)
                {


                    this._children = new MCollection();

                },
            }
        ); 
    }
);

so what is happening.. I load the model M, but in the model i'm also creating a collection which has as model: M, so it depends on each other.. as a result the model of MCollection remains undefined, while it should be referrering to M.

I tried thinking how i can fix this but i can't find a way to do this.. Do you?

Upvotes: 1

Views: 945

Answers (1)

Johan Henriksson
Johan Henriksson

Reputation: 687

Circular dependencies are usually a sign of bad design. I recommend that you rethink this problem and try to solve it some other way. For example, do you need to create models using the collection? You only need the model field in a collection if you want to be able to pass arbitrary objects and have them instantiated as models. If you always add M models to the collection, you wont need to reference it in the collection.

Upvotes: 1

Related Questions