Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,

like image 467
user1031947 Avatar asked Jan 14 '13 18:01

user1031947


1 Answers

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.

like image 135
Andreas Köberle Avatar answered Sep 28 '22 00:09

Andreas Köberle