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

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...