1

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?

Captain Obvious
  • 745
  • 3
  • 17
  • 39

1 Answers1

1

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.

Johan Henriksson
  • 687
  • 3
  • 10
  • it should be this._children = new exports.MCollection() ? and now i get Uncaught TypeError: undefined is not a function, which is located at the line: this._children = new exports.NodeCollection(); – Captain Obvious Sep 17 '13 at 17:10
  • Sorry, I thought this would be the way to do it. It's a bit hard for me to test the example since I don't have a requirejs environment set up. You should look into other ways of solving this problem without causing circular dependencies. – Johan Henriksson Sep 17 '13 at 17:19