Circular Dependency in Backbone / RequireJS Nested

2019-01-23 18:38发布

问题:

I'm setting up a nested categories structure in Backbone with RequireJS.

In this structure, a categories collection contains category models, and a single category model can contain a categories collection.

Unfortunately this seems to cause the dreaded circular dependencies problem in RequireJS. I have read the docs on RequireJS (http://requirejs.org/docs/api.html#circular) however I am finding the explanation with 'a' and 'b' confusing.

Here is my code, which is causing the problem:

define([

    "jquery",
    "underscore",
    "backbone",
    "collections/categories"

    ], function( $, _, Backbone, CategoriesCollection ) {

    var Category = Backbone.Model.extend({

        defaults: {
            title: "Untitled"
        },

        parse: function(data) {
            this.children = new CategoriesCollection( data.children, {parse: true} );
            return _.omit( data, "children" );
        }

    });

    return Category;

});

...

define([

    "jquery",
    "underscore",
    "backbone",
    "models/category"

    ], function( $, _, Backbone, CategoryModel ) {

    var Categories = Backbone.Collection.extend({
        model: CategoryModel
    });

    return Categories;

});

I am wondering if anyone who has experienced this before can help steer me in the right direction.

Thanks (in advance) for your help,

回答1:

You just need to use require the collection again when you need it in the model, as the Collection passing initially can be undefined:

define([

    "jquery",
    "underscore",
    "backbone",
    "collections/categories"

    ], function( $, _, Backbone, CategoriesCollection ) {

    var Category = Backbone.Model.extend({

        defaults: {
            title: "Untitled"
        },

        parse: function(data) { 
            if(!CategoriesCollection){
              CategoriesCollection = require("collections/categories");
            }

            this.children = new CategoriesCollection( data.children, {parse: true} );
            return _.omit( data, "children" );
        }

    });

    return Category;

});

In the example they import also require but it should also work without the import.



回答2:

For this you should consider to use a plugin like Backbone Relational.