Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

javascript - Circular Dependency in Backbone / RequireJS Nested List

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...