Need advice on working on large javascript files
I have about 2000 lines of javascript code for my application. A lot of this is user interaction / jQuery. Don't wo开发者_如何学运维rry, it all works fine :)
But it's getting dificult to keep track of the code base. So I have split up the file into five files.
I thought that if I load all files, they all reside in memory and the can communicate with each other. but it does not look like it. Because, in file A, I have var currentPage = getURLvar('slpage');
and in file B I have if ( currentPage == 'someName')
.
But file B does not recognize the variable currentPage.
Also I have som general scripts in file C which file A nd B can use. But I guess that's not possible to cal leither?
Any advice is much appreciated.
UPDATE
My javascript start s like this:
// FILE A
jQuery(document).ready(function() {
var currentPage = getURLvar('slpage');
if ( (currentPage == 'Aa') || (currentPage == 'Bb') ) {
init_AA();
}
else if ( (currentPage == 'Cc') || (currentPage == 'Dd') ) {
init_BB();
} else if ( (currentPage == 'Ee') || (currentPage == 'Ff') ) {
init_CC();
}
(...)
// FILE B
function init_AA()
{
(...)
}
function getURLvar(name)
{
//Gets the URL and returns the value of specified paramter.
}
You're right that it's possible to access parts of a script in other files. The problem you're having sounds like one of scoping.
If your variable is in the global namespace (which isn't a great idea) then you'll be able to access it directly like you've tried.
Alternatively, if you have your variable scoped inside a method, it will only be accessible too that method.
In order to expose the variable you want, I'd sugest creating a common namespace for the code and scoping your seperated Javascript into the relevant namespace.
Here's some resources for more information:
http://www.dustindiaz.com/namespace-your-javascript/
http://snook.ca/archives/javascript/javascript_name
UPDATE:
Based on the code you've posted you could simply move the variable decleration outside the scope of the anonymouse function.
var currentPage;
jQuery(document).ready(function() {
currentPage = getURLvar('slpage');
...
精彩评论