对于我正在编写的 Titanium 应用程序,我已经构建了一种模块化方法,以便其他开发人员(当我离开我的组织或其他人被要求添加到应用程序时)可以轻松地向应用程序添加新模块(不要与 native 代码模块混淆)。
我很难弄清楚如何从数组加载模块并调用通用的中央引导类型方法来初始化模块。该应用程序使用 Tweetanium 作者建议的命名空间方法。
该应用程序使用命名空间:org.app
我已经定义了一个数组,其中包含要在应用程序中加载的已配置模块:
org.modules = [
{
name: 'messages',
enabled: true,
title: 'Messages'
},
{
name: 'calendar',
enabled: true,
title: 'Calendar'
}
];
每个模块都有命名空间:
org.module.moduleName
哪里moduleName
是数组中模块的名称(例如消息或日历)。我已经创建了一个模块目录,并且我已经成功地为每个启用的模块动态包含了 js 文件(通过专门静态调用方法进行测试)。我需要调用
createModuleWindow()
方法从模块代码获取该模块的主 View 。org.module = {};
org.module.moduleManager = [];
// Loop through the list of modules and include the
// main modulename.js file if enabled.
// Create the module and add it to the module manager array
var modules = org.modules;
var config = org.config;
for (var i = 0; i < modules.length; i++) {
var _module = modules[i];
if (_module.enabled) {
Ti.include(config.moduleBasePath + _module.name + "/" + _module.name + '.js');
org.module.moduleManager.push(createModuleWindow(_module.name));
}
}
function createModuleWindow(moduleName) {
// Not sure what to do here.
return org.module.[moduleName].createMainWindow();
};
对于
createModuleWindow()
,我已经尝试过动态类和方括号表示法,但我只是得到错误,如“moduleName”不是构造函数(在使用类方法的情况下)或在上述代码的情况下解析错误。如何动态调用命名空间模块方法?
最佳答案
您的语法错误在这里:
return org.module.[moduleName].createMainWindow();
^
应该没有点:
return org.module[moduleName].createMainWindow();
其他一些注意事项:
org.module
在您的示例代码中为空,因此上面的行将引发空指针异常。 (您可能只是没有显示所有代码。)org.module
(单数)和 org.modules
(复数)是不必要的困惑。我会尽量在代码中更好地区分两者。 关于javascript - 从变量动态创建命名空间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8482306/