2

I have this backbone application built on Rails with sprockets, and I'm using backbone-forms and associations. The files (models and collections etc) are included in a certain order (thanks to the sprockets). The problem is that when I create a form for one model I have to reference the constructor of another model and it's not working (because the model's file has not been included yet).

The code will make a little more sense. So, here is my document model:

var Document = Backbone.AssociatedModel.extend({
    //...

    schema: {
        description: 'Text',
        tags: {
            type: 'NestedModel',
            model: Tag
        }
    }

    //...
});

And this is my tag model:

var Tag = Backbone.AssociatedModel.extend({
    //...

    schema: {
        name: {
            type: 'Select',
            options: [1,2,3,4]
        }
    }

    //...
}

The problem is that sprockets includes my tag model AFTER it includes the document model and therefore Tag is undefined.

What should I do? Is there a work-around?

Fabian de Pabian
  • 599
  • 4
  • 20

1 Answers1

1

I recommend using RequireJS to manage dependencies.

e.g.

define([
    'extensions/assocmodel'
], function(AssociatedModel) {
    'use strict';

    var TagModel = AssociatedModel.extend({
        //...

        schema: {
            name: {
                type: 'Select',
                options: [1,2,3,4]
            }
        }

        //...
    });

    return TagModel;
});

Then:

define([
    'extensions/assocmodel',
    'path/to/tag/model'
], function(AssociatedModel, TagModel) {
    'use strict';

    var DocumentModel = AssociatedModel.extend({
        //...

        schema: {
            description: 'Text',
            tags: {
                type: 'NestedModel',
                model: TagModel
            }
        }

        //...
    });

    return DocumentModel;
});
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • What if you have 3 models each depending on each other? None of the files will be required correctly by requireJs because they all depend on each other. – Fabian de Pabian Jul 31 '14 at 10:07
  • 1
    That's not true, all large apps have inter-dependence it works fine, very occasionally and often through bad architecture you get a circular dependence which can be broken by requiring in the define in the initialize method e.g. `AssociatedModel = require('AssociatedModel')` – Dominic Jul 31 '14 at 10:33