使用require的Dojo循环依赖 [英] Dojo cyclic dependency using require

查看:120
本文介绍了使用require的Dojo循环依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用dojo,这些是我的模块-

I'm using dojo and these are my modules -

'myview/ModuleA' --requires--> 'myview/ModuleB'
'myview/ModuleB' --requires--> 'myview/ModuleC'
'myview/ModuleC' --requires--> 'myview/ModuleD'

现在,我正在尝试制作

'myview/ModuleD' --requires--> 'myview/ModuleB'

但是,当模块D尝试实例化 ModuleB 作为具有 TypeError的新ModuleB():ModuleB不是构造函数
我看到 ModuleB 只是一个对象而不是函数 ModuleD 中的code>。所以我知道为什么我得到错误。我也意识到这可能是由于循环依赖性,这就是 ModuleB 未加载到 ModuleD 中的原因。

But the code fails in ModuleD when it tries to instantiate ModuleB as new ModuleB () with TypeError: ModuleB is not a constructor. I see that ModuleB is just an object and not a function in ModuleD when it is trying to instantiate it. So I know why I get the error. I also realize this is probably because of cyclic dependency and that's the reason ModuleB is not loaded in ModuleD.

我能够通过从 define(。)的需求列表中删除 ModuleB 来解决此问题。 ..) ModuleD ,而是在其之前使用 require()加载它实例化。

I was able to work around this by removing ModuleB from the requires list in the define(...) of ModuleD and instead load it using require() just before it is instantiated. This works.

我的问题-这是做一些涉及模块的循环依赖的正确方法吗?还是建议使用更好/不同的方法?

My Question - Is this the right way of doing something that involves cyclic dependency of modules or is there a better/different way that is recommended?

谢谢

推荐答案

需要即时而不是这样做定义时间是处理循环依赖关系的正确方法。

此处说明: http://requirejs.org/docs/api.html#circular

Requiring "on the fly" instead of doing it a define time is the proper approach for circular dependencies.
This is explained here: http://requirejs.org/docs/api.html#circular


如果您定义循环依赖关系( a需要 b, b需要 a),则在这种情况下,当调用 b的模块函数时,它将获得一种。通过使用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")

重要提示:在构建时,您将必须在构建配置文件中指定运行中需要的所有组件。否则它们将不会包含在要构建的文件列表中。

Important: At build time, you will have to specify in the build profile all components you had to require on the fly. Otherwise they will not be included in the list of files to build.

这篇关于使用require的Dojo循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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