Backbone-rails model referencing with sprockets

97 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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;
});