Sam Sirry
Sam Sirry

Reputation: 762

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?

Upvotes: 0

Views: 126

Answers (3)

Sam Sirry
Sam Sirry

Reputation: 762

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:

  • It is necessary that the code ends with something like return true otherwise the server generates an error parsing js code.
  • The <xp:view> resources get loaded in the order they are listed in the XML source. If you have code that depends on other code, make sure to order them properly.
  • My previous answer (below) has the complication that quotations and new lines must be escaped, and it doesn't help that the javascript engine shipped with Domino 9 is outdated (ES ver 3).

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.

Upvotes: 1

Chris Richards
Chris Richards

Reputation: 705

I second what Georg says. Put the function in a library, but only include it as a resource on the custom control/xpage that will be doing the calls so it is not loaded on other pages/controls where not needed

Upvotes: 2

Georg Kastenhofer
Georg Kastenhofer

Reputation: 1417

In my opinion it isn't possible, because you have no "global scope" and therefore you can't reference your function from different events in your xpage/custom control. You have to put this SSJS function in a library!

Upvotes: 1

Related Questions