1

I defined a Javascript function in the function body of a tab view, but when I try to call it the function is undefined. I moved the function so it is defined in index.php, and now it works just fine. What's going on here?

Tom Swift
  • 25
  • 3

1 Answers1

1

Your observation is correct. JavaScript functions that are declared in tab views (icl/show[module].inc.php) are not loaded automatically. You may put the functions in index.php so that the function is available globally. However, this is not recommended practice for two reasons: 1. You'll also have to change iphone.php, in which case you'll end up with two copies of the same code; 2. it's better to load module-specific JavaScript functions on demand.

In icl/list[module]s.inc.php, there's this line:

ajxjs(self.show[module],'[module]s.js');

The above line detects whether a function show[module] is loaded. If not, it will load all the functions that are defined in [module]s.js. This makes sure that the JS file is loaded only once.

The functions have to be written in the following format:

show[module]=function(param1, param2){...}

instead of this:

function show[module](param1, param2){...}

If your tab can be opened without going through the list view, you'll have to manually load the JS file. For example, you have a function called update[module], but the [module] tab is opened via [anothermodule]:

<a onclick="ajxjs(self.update[module], '[module]s.js'");>open</a>

Technically you may also use the self.show[module] flag. It works just as well.

For completeness, there is another less recommended way to load JavaScript functions. If you use ajxpgn, there's a 4th parameter that forces loading the script blocks. Gyroscope has been structured to avoid such use case. If you find yourself needing script blocks inside a content file, consider organizing the code differently.

Schien
  • 3,855
  • 1
  • 16
  • 29
  • Why do the functions need to be written like `show[module]=function(param1, param2){...}` instead of `function show[module](param1, param2){...}` ? – Tom Swift Aug 17 '15 at 16:44
  • 1
    In most browsers there is no difference between: eval("function test(){alert('test');}") and eval("test=function(){alert('test');}"); Some browsers will ignore the former. However, JavaScript is a first class language, meaning its variables can be ANYTHING including functions. The latter style is simply a variable assignment, and is honored by EVERY browser. – Schien Aug 17 '15 at 16:50