requirejs module is undefined

2019-07-05 16:51发布

问题:

I have following directory structure

scripts
    modules
        tabs.js
    app.js

I have following code in app.js

define([
    'jquery', 
    'underscore',
    'modules/tabs',
    ], function($, _, Tabs) {

    var App = (function() {

        var init = function() {
            console.log('app');
            Tabs.init();
        };

        return {
            init: init
        };

    }());

    return App;
});

following code in tabs.js

define([
    'jquery', 
    'underscore',
    '../app'
    ], function($, _, App) {

    var Tabs = (function() {

        var init = function() {
            console.log('tabs init');
            App.init();
        };

        return {
            init: init
        }

    }());

    return Tabs;

});

As it can be seen that both app.js dependent on tabs.js and tabs.js is dependent on app.js What happens is when I call Tabs.init() in app.js then it works fine but when I do App.init() in tabs.js then App is undefined. How can I make this work so that when I do App.init() in tabs.js then it should work?

回答1:

If you define a circular dependency ("a" needs "b" and "b" needs "a"), then in this case when "b"'s module function is called, it will get an undefined value for "a". "b" can fetch "a" later after modules have been defined by using the require() method (be sure to specify require as a dependency so the right context is used to look up "a"):

//Inside b.js:
define(["require", "a"],
    function(require, a) {
        //"a" in this case will be null if "a" also asked for "b",
        //a circular dependency.
        return function(title) {
            return require("a").doSomething();
        }
    }
);

http://requirejs.org/docs/api.html#circular