requirejs模块未定义

编程入门 行业动态 更新时间:2024-10-15 18:21:58
本文介绍了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(); } } );

requirejs/docs/api.html#circular

更多推荐

requirejs模块未定义

本文发布于:2023-07-16 02:01:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1116642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   未定义   requirejs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!