我有以下目录结构
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(); } } );
requirejs/docs/api.html#circular
更多推荐
requirejs模块未定义
发布评论