Skip to content

Instantly share code, notes, and snippets.

@denisnazarov
Last active December 15, 2015 08:39
Show Gist options
  • Save denisnazarov/5232877 to your computer and use it in GitHub Desktop.
Save denisnazarov/5232877 to your computer and use it in GitHub Desktop.

What is the proper way to load requirejs modules for models/views/collections in a backbone project?

I am using Yeoman to create a scaffolding for the app and am only starting to use require js.

My main.js file:

require.config({
    paths: {
        jquery: '../components/jquery/jquery',
        underscore: '../components/underscore/underscore',
        backbone: '../components/backbone/backbone',
        bootstrap: 'vendor/bootstrap'
    },
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: ['jquery', 'underscore'],
            exports: 'Backbone'
        },
        bootstrap: {
            deps: ['jquery'],
            exports: 'jquery'
        }
    }
});

define(['App', 'jquery', 'bootstrap'], function(App, $){
    $(document).ready(function(){
        App.start();
    });
});

My scripts/App.js file:

define(['backbone'], function () {
    App = {
        init: function () {
            // initialize router, views, data and layouts            

        },
        start: function () {
            App.init();
            Backbone.history.start();
        },
        Views: {},
        Models: {},
        Collections: {},
        Routers: {}
    }

    
    return App;
});

One of the models scripts/models/Gallery-model.js:

define(['App'], function(App){
  var GalleryModel = Backbone.Model.extend({
		initialize: function() {
			this.items = new App.Collections.GalleryItemsCollection( this.get('children') );
		}

	});

	App.Models.GalleryModel = GalleryModel;
	return GalleryModel;
});

The other views, models, and collections are defined in a similar way. If I console.log(App), none of the Models, Views, or Containers methods are defined. Where should I be laoding all those modules in the code?

@BorisKozo
Copy link

You cannot require App module because it wasn't shimmed. You also don't need to shim it because it is your code. Simply replace the define calls from:

define(['App']  

to

define(['../scripts/App']

or whatever is the correct path to that file (note that it should not include the .js at the end)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment