xpages-ssjs

XPages: Can an SSJS function be reused on a single XPage without putting it in a library?


I have a ssjs function that is only called a couple of times in a self-contained XPages custom control.

Is there a way to keep this function in the XPage/CustomControl itself and call it directly without storing it in a separate javascript library?


Solution

  • This is how server-side javascript can be made available everywhere in the XPage (or Custom Control) without the need to place it in a Script Library:

    Right under <xp:view>:

    <xp:this.resources>
        <xp:script clientSide="false">
            <xp:this.contents>
                <![CDATA[${javascript:
                    var testA = "123";
                    function testB(){
                        return "123";
                    }
                    return true;
                }]]>
            </xp:this.contents>
        </xp:script>
    </xp:this.resources>
    

    Notes:


    Previous answer from 2017:

    Add a ComputedField (e.g. name it 'local_ssjs') and let it generate the desired shared js code as a string value.

    E.g.: "function returnFour(){retrun (4)};"

    In your event, obtain the shared code and use the eval() function to include it.

    var sharedCode = getComponent("local_ssjs").getValue(); eval(sharedCode); var xFour = returnFour();

    Even if the computed field only contains function definitions, this works ok.