想象一下,我们有三个小部件:Foo,Bar和Baz。现在我们有一个长度为10的阵列,其中包括' Foo'' Bar'和' Baz'话。我们想根据数组中的string-element实例化相应的Widget:
array.forEach(arrayOfStrings, function(arrayElement) {
require(['some_path/' + arrayElement], function(cls) {
new cls();
});
在require
循环中使用forEach()
是不好的做法?是否有任何改善此代码的好方法(可能是已经使用过的元素存储)?
答案 0 :(得分:1)
由于Bergi建议循环中的require不一定是不好的做法,require
也会缓存你的AMD模块。
备选方案:
01)您可以使用更具说明性的方法,例如使用循环来创建HTML标记并将结果附加到DOM,例如:
<input type="text" name="field1" data-dojo-type="app/foo" />
并使用dojo/parser
以Auto Require
模块foo
more info on auto require here。
02)使用简单的factory。您可以摆脱循环中require
的并在工厂中委派它的用法。一些伪代码:
array.forEach(arrayOfStrings, function(arrayElement) {
UserFactory.createFoo(); // use the factory instead
});
//... factory object here
UserFactory.createFoo = function() {
require(['some_path/foo'], function(cls) {
new cls();
});
};
更多&#34;动态&#34;版本(只是一些伪代码)
array.forEach(arrayOfStrings, function(type) {
UserFactory.createWidget(type); // use the factory instead
});
//... factory object here
UserFactory.createWidget= function(type) {
require(['some_path/' + type], function(cls) {
new cls();
});
};