Skip to content

Instantly share code, notes, and snippets.

@edm00se
Last active February 7, 2016 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edm00se/02d1c8353b199a275452 to your computer and use it in GitHub Desktop.
Save edm00se/02d1c8353b199a275452 to your computer and use it in GitHub Desktop.
Sample utility library

Utility Library Example

Adding a utility library is a great and convenient way to provide convenince functions for use at a global or near-global level.

Adding

Hooking a utility SSJS library works about the same as any Code > Script Library asset in XPages. You can add it via a Theme, my personal recommendation as it makes keeping things tidy quite easy, or by adding it as an xp:resource (resources at the root XPage or Custom Control via the pretty pane). The down side of relying on adding it to a Custom Control is that it will only be available in an SSJS code block if the Custom Control in question has been loaded as part of the user's component tree (the built page); this also leads to potential duplication if the developer starts loading it on lots of Custom Controls.

Via Theme

Adding via a theme is easy enough, just edit your existing or create a new one for your app and have it extend the theme you were already using (e.g.- an out of the box one, like OneUIv3, etc.).

<theme extends="...someTheme" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<resources>
		<script target="xsp" src="/utility.jss" clientSide="false" type="text/javascript" />
	...
	</resources>
</theme>

Use

The utility library is now accessible from your SSJS script blocks (#{javascript:return u.asVec(document1.getItemValue("SomeFieldName"));}).

var u = {
asVec: function(obj){
/**
* @author Eric McCormick
* twitter: @edm00se
* src: https://edm00se.io/xpages/consistent-multivalue-formatting/
*
* @param java.util.Object to examine
* @return java.util.Vector of values from originating Object
**/
switch(typeof obj){
case "java.util.Vector": //it's already a Vector, just return it
return obj;
break;
case "java.util.ArrayList": //it's an ArrayList, return it as a Vector
case "Array": //it's an Array prototype, return it as a Vector
var x:java.util.Vector = new java.util.Vector();
var s = obj.size()||obj.length;
for(var i=0; i<s; i++){
x.add(obj[i]);
}
return x;
break;
case "java.lang.String":
default: //it's most likely a String or other individual value, return it as a Vector
var x:java.util.Vector = new java.util.Vector();
x.add(obj);
return x;
break;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment