Blog Layout

How to define and use a SSJS function inside an XPage

John Dalsgaard • 5. september 2024

Define and use an SSJS function without using a library

I have long been annoyed by not being able to define a server side Javascript (SSJS) function inside an XPage or more often a Custom Control.

You can always add the function to a script library, however, the function may only apply to one control and as such will "pollute" the overall system in a script library.


Then today an idea crossed my mind and I tested it out - and it works...!!


Basically, I tried to add the function to a datacontext variable like this:

    <xp:this.dataContexts>

        <xp:dataContext var="localSSJS">

            <xp:this.value><![CDATA[#{javascript:   

                // Sneak a method in here that can be called from the entire this CC

                var getCellStyle = function(id){

                    var selected = document.getValue(FN_RiscCellId) == id;

                    return 'matrixCell'+getLabel('color5x5Matrix'+id, compositeData.formName) + (selected ? ' circle' : '');

                }

            }]]></xp:this.value>

        </xp:dataContext>

    </xp:this.dataContexts>

And then the code is used later in the Custom Control like this:

    <xp:td id="td11">

        <xp:this.styleClass><![CDATA[#{javascript:getCellStyle('2.5')}]]></xp:this.styleClass>

            :
   
        :
    </xp:td>

And voila - we have a function defined inside one XPage or Custom Control that we can use in several places to avoid duplicating logic - and still don't have to put in a globally visible script library!

Blog

Af John Dalsgaard 22. oktober 2024
In today's IT landscape it is quite normal that you have to call "services" in client driven website - and that can easily be across domains...
Af John Dalsgaard 5. september 2024
Definer en lokal SSJS funktion uden at bruge et 'library'
Flere indlæg
Share by: