<< 09 May 2011 | Home | 11 May 2011 >>

XPages JavaScript utility function of the day

Yesterday and today I've been spending some time doing some XPages coding for a customer project and after spending quite some time doing Java plugin development I'm amazed of how easy XPages are. Don't get me wrong - there is still work to do for the XPages team but it's a joy to work with XPages and coding in JavaScript is just - well - flexible and fun.

One of the real joys of JavaScript is it's dynamic nature and that it allows one to really cut down on the boilerplate and repeated code. For one I spent a lot of key pressed getting field values from backend documents in server side JavaScript. Instead of repeating the same ol' Document.getItemValueString(String) over and over again I did a neat little shortcut. Since I needed all items from a document I just created a utility function to JSONify a document to make it easier to access. The method is below.

var jsonifyDocument = function(doc) {
   var result = {};
   if (!doc) return result;
   var item;
   for (item in doc.getItems().toArray()) {
      result[item.getName().toLowerCase()] = item.getText();
   }
   return result;
};
So now instead of writing doc.getItemValueString all the time I can now just do property-like access to field values ("Heading" and "Description" are fields on the document).
var jsonDoc = jsonifyDocument(doc);
jsonDoc.heading + " (" + jsonDoc.description + ")";

I also wrote a nice little Dojo-like mixin function to make my XAgents easy to configure. But that's for another day.