gpt4 book ai didi

javascript - 如何在初始函数之外以正确的 AMD 方式使用自定义 Dojo 模块?

转载 作者:行者123 更新时间:2023-11-28 06:17:12 25 4
gpt4 key购买 nike

我终于明白了that and why named classes are not a good practice我想更新我的代码。然而,即使在reading之后several documentation pages , blog entries and SO questions ,我不明白如何以正确的 AMD 方式执行此操作当我需要在需要模块的功能之外使用该模块时。AMD 是否支持这一点,或者我应该完全重新安排我从哪里使用 AMD 类的文件?

我之前做了什么 - 配置:

var dojoConfig = {
paths: {
fooBar: '@Url.Content("/portal/Modules/Foo.Bar/Scripts/foo-bar")'
}
};

在模块中:

define("fooBar/foo", [/*required modules*/], function(/*required modules*/) {
//the rest of code

return declare("fooBar.foo", [/*superclass*/], {
//the rest of code

在我使用它的文件中:

var required = [
/*first 5 required modules*/
"fooBar/foo",
/*the rest of required modules*/
]

require(required, function (/*5 first modules*/, Foo) {
//code

var barBaz = _customFunction(/*parameters*/);

//code
});

//Foo and other names set by require are not available here
function _customFunction(/*parameters*/) {
//code

var foo = new fooBar/foo({/*parameters*/});

//code
}

我从类中删除了模块名称,我再也看不到它了。甚至 fooBar 也是未定义的,除非我需要来自同一命名空间的命名函数 bar 。我将 async: true 添加到配置中,但没有任何变化。我知道 AMD 类构造函数不应该包含在需要模块的函数中(不要问我源代码,上面链接的某个地方),但是如何创建该类的对象?

应该工作的是另一个 require 调用,但我不知道如何使用它。我不确定这是否被认为是好的做法 - 做出一些肮脏的解决方法会破坏转向未命名声明的意义。

有效的方法是将所有内容放入包装函数中,或者可能放入类中,其中没有任何代码位于 require 语句的范围之外。就我而言,我将函数 _customFunction 移动到具有空构造函数的命名类,以避免包装并可能破坏同一文件中的数十个函数;一旦有时间,我们也会改造其他的......并确保我们真正改进了代码。

所以,鱼被钓到了,但我在这堂钓鱼课上仍然停留在一半。

TL;DR: 我需要了解什么是好的实践,什么是不太好的实践,但对于转录位于名称范围之外的类构造函数调用仍然有效(以及为什么)由 require 语句设置。

最佳答案

在问这个问题之前,我似乎唯一没有读过的 Dojo 教程 contains the right advice为了我!

关键部分:

Again, repeat after me "the global namespace is bad, the global namespace is bad, I will not use the global namespace, I will not use the global namespace".

因此将其包装在 require 语句中。

Within the closure of the require(), we reference the modules based on the variable name we declared in the argument.

这可以在声明中,但这不是必需的。

The other core function in AMD is define() which is usually used for defining modules. See the Defining Modules tutorial for more information on how to use define().

因此,尽管仍然有一些我不确定的技术细节,但现在我了解了基本思想,并且知道下一步要寻找什么。其余的应该很容易。我可能会稍后更新以改进这个答案,以帮助其他人解决同样的问题,但我现在很高兴:-)

关于javascript - 如何在初始函数之外以正确的 AMD 方式使用自定义 Dojo 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com