requirejs模块未定义 [英] requirejs module is undefined

查看:1030
本文介绍了requirejs模块未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下目录结构

scripts
    modules
        tabs.js
    app.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;
});

以下代码在tabs.js

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;

});

可以看出,依赖于tabs.js和tabs.js的app.js都是依赖的在app.js上发生的事情是当我在app.js中调用Tabs.init()然后它工作正常但是当我在tabs.js中执行App.init()时,App是未定义的。我怎样才能使这个工作,以便当我在tabs.js中执行App.init()时它应该工作?

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?

推荐答案


如果定义循环依赖(a需要b而b需要a),则
然后在这种情况下调用b的模块函数时,它将为a获得
未定义的值。模块通过使用require()方法定义
之后,b可以获取a(确保指定require
作为依赖项,因此使用正确的上下文查找a ):

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

这篇关于requirejs模块未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆