tags:

views:

78

answers:

1

Hi. I have about 2000 lines of javascript code for my application. A lot of this is user interaction / jQuery. Don't worry, 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.
  }
+3  A: 

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%5Fname

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');
 ...
Jamie Dixon
humm... I was wondering if something like this existed. I'm not sure what you mean by Scoping though.
Steven
Scoping simply refers to the scope that the code has. For example, declaring a variable at the top of a function means that the function is the scope that the variable can be used. Outside of this function the variable doesn't exist. We refer to this as the variable having scope (scoped to the function).What's really being said is "where can this variable be seen from". In your example it seems the variable can only be seen my the function it's defined in. Other functions don't have that scope (can't see the variable) because it's locked away.
Jamie Dixon
See my update above. This should get you up and running right away.
Jamie Dixon