requirejs module is undefined

家住魔仙堡 提交于 2019-12-13 15:02:15

问题


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



来源:https://stackoverflow.com/questions/24819317/requirejs-module-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!