Wednesday, December 22, 2010

XPages and Server Side Javascript libraries

So, you have created an XPage and you have a Javascript function that you want to reuse in multiple places within the XPage (say, for example, to hide a number of different controls on the page using identical logic).  Where do you place the Javascript function so that you can access it from Server Javascript and not have to rewrite (and maintain) identical code multiple times?  The answer is a "Server Javascript" script library.

You create a "Server Javascript" script library in the same way you would any other script library.  The secret is to change the script library type to "Server Javascript".

Figure 1 - Creating a Server Javascript script library

Give the script library a name and click OK.  The "Server Javascript" editor panel opens.

Figure 2 - The Server Javascript editor panel
This is the editor panel that you should be familiar with from adding Server Javascript to XPages.  Add the Javascript function to your library in the same manner you would if you were adding it direct to your XPage.  When you are finished, save and close the editor.

So, how do you reference your script library from your XPage?  The key is the import keyword.  At the start of your Server Javascript routine, you need to enter the following statement:
import xpages;
where xpages is the name of your Server Javascript script library.  You will then be able to call all of the functions you placed in the script library in your routine.