Continuing my XPages theme from yesterday I also wrote an XAgent base-class in JavaScript to make XAgents easier to do. Part of the base class is that it allows me to pass in a JSON object to configure the XAgent based on the need. Since the information I pass in should override the built-in defaults I needed a way to easily allow the user supplied values to override the defaults. The easiest way to do this would be to use the dojo.mixin.
"dojo.mixin is a simple utility function for mixing objects together. Mixin combines two objects from right to left, overwriting the left-most object, and returning the newly mixed object for use."
Unfortunately Dojo isn’t available in SSJS I needed to do it myself. To my luck it was surprisingly easy as the below code illustrates.
// create function to allow mixin' two objects var mixin = function(target, source) { if (!source) return; var name, s, i; for (name in source) { s = source[name]; if (!(name in target) || (target[name] !== s)) { target[name] = s; } } };
My XAgent base class looks something like this:
function XAGENT(args) { // create mixin function var mixin = function(target, source) { if (!source) return; var name, s, i; for (name in source) { s = source[name]; if (!(name in target) || (target[name] !== s)) { target[name] = s; } } }; // define default arguments this._args = { download: false, filename: "default.json", charset: "iso-8859-1", contentType: "application/json" }; // mixin user-supplies arguments mixin(this._args, args); }; XAGENT.prototype.run = function(command) { ... };
What’s super neat is that now, in my run-method I can access the this._args object and all values that the user supplied have overridden the default values because we used the mixin-function. Very cool and an easy and flexible way to have default values but allowing them to be overridden by the caller. Also you know that the variables you need have been defined so no checks are necessary.
Calling my XAgent class is very easy allowing me to override the defaults. The run-method accepts a function which is called when the XAgent stuff has been set up supplying the Writer and the parameters supplied in the URL as a JSON object.
var xa = new XAGENT({ filename: "feed.json", download: true }); xa.run(function(w, params) { ... });