我创建了一个JavaScript应用程序,其中包含一个文件中的所有代码。该应用程序已经有了很大的发展,我认为是时候把它分成多个文件,但我很难搞清楚如何做到这一点。我认为问题在于我怎么决定构建应用程序,它使用了下面的模板:如何将JavaScript应用程序拆分为多个文件?
var myApp = function(){
//there are several global variables that all of the modules use;
var global1, global2, module1, module2;
global1 = {
prop1:1
};
//There are also several functions that are shared between modules
function globalFunction(){
}
var ModuleOne = function(){
function doSomething(){
//using the global function
globalFunction();
}
return{
doSomething:doSomething
}
};
var ModuleTwo = function(){
function doSomething(){
//module 2 also needs the global function
globalFunction();
//Use the functionality in module 1
//I can refactor this part to be loosely coupled/event driven
module1.doSomething();
}
};
module1 = new ModuleOne();
module2 = new ModuleTwo();
};
即使所有的模块都松散耦合和事件驱动的,我还是不知道怎么会有我在每个模块依赖共享函数/变量的情况下,将其分解为多个文件。有没有人有建议?
尽管如此,工具如[module8] (https://github.com/clux/modul8)解决你的问题 – Raynos 2012-01-06 02:25:39
看看这篇文章中的设计模式:http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-深度 - 你可以将模块定义分割为多个文件,以便共享通用属性,还可以创建仅针对特定文件的变量或方法。 – nnnnnn 2012-01-06 02:30:33
@nnnnnn谢谢。我会立即检查出来。 – 2012-01-06 03:21:34