我創建了一個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