socrateisabot
socrateisabot

Reputation: 847

Cannot access to another class inside Requirejs module

I can't access my "App" object despite I require it inside my module with the defined statement. Could you explain me please why my code is not working.

This is my main.js file :

require(['underscore', 'backbone', 'App'], function(_, Backbone, App) {

    window.App = new App();
    Backbone.history.start();
    return window.App.init();

});

This is my app.js file :

define(['underscore', 'backbone', 'Views/ApplicationView'], function(_, Backbone, ApplicationView) {
    'use strict';
    var App;
    return App = (function() {

        function App() {

            this.init = __bind(this.init, this);
        }

        App.prototype.init = function() {

            this.view = new ApplicationView();
       };

       return App;

    })();
});

And finally my applicationView.js

define(['underscore', 'backbone', 'views/AbstractView', 'App'], function(_, Backbone, AbstractView, App) {
    'use strict';
    var RegisterView;
    return RegisterView = (function(_super) {
        __extends(RegisterView, _super);

        function RegisterView() {
            this.init = __bind(this.init, this);
            return RegisterView.__super__.constructor.apply(this, arguments);
        }



        RegisterView.prototype.init = function() {

            RegisterView.__super__.init.apply(this, arguments);
            this.model = App.user; // APP IS UNDEFINED
        };

    })(AbstractView);
});

Upvotes: 0

Views: 196

Answers (1)

Louis
Louis

Reputation: 151380

The only issue I'm seeing with this code is a circular dependency. In general you want to design your code to avoid them. If you can't then, the code above should be modified so that the line that assigns this.model (in RegisterView.prototype.init) is like this:

this.model = require("App").user;

It has to be this way because the App that the module's factory function (the anonymous function given to define) will get will necessarily be undefined because by the time RequireJS loads this module, the module for App has not yet finished loading. Performing the require call like above causes RequireJS to fetch the value later, when the module for App has finished loading.

Documented here.

Upvotes: 2

Related Questions