URL-Embedded Preferences - Ajax Patterns

URL-Embedded Preferences

From Ajax Patterns

Contents

Ajax/Javascript Programming and Usability in "Ajax Design Patterns" Book

Code Example

http://ajaxify.com/run/widgets/opensuite/message/message.xml

The URL above is the "canonical URL", but unlike most gadgets, we actually need to append some parameters to make it useful. For example:

 http://ajaxify.com/run/widgets/opensuite/message/message.xml?title=Greetings&message=Hi%20Everybody!!!

An alternative representation, also feasible, might have looked like this:

 http://ajaxify.com/run/widgets/opensuite/message/message.xml/Greetings/Hi%20Everybody!!!

As you can guess, the gadget shows a message (and title) derived from the URL parameters.

     populatePrefsFromURLParams();
     ...
     $("message").innerHTML = pref("message");

The first line, populatePrefsFromURLParams(); sets preferences from all the parameters that were found in the input URL. After it has been called, the "message" preference will have been populated and can be used to show the message.

Let's dive into the innards of populatePrefsFromURLParams(). The grunt work is actually performed by another function, populateURLParams(), which inspects the URL and sets up a parameter map, i.e. a map from parameter keys to parameter values. Once we have this map - urlParams - all we have to do is copy it to the preference structure. So we walk through each pair and set a corresponding preference.

     populateURLParams();
     for (var key in urlParams) {
       if (prefs.getString(key)) prefs.set(key, urlParams[key]);
     }

Okay, but how does populateURLParams() work? Pretty straightforward. It performs some "introspection" to get the URL, which is exposed by the OpenSocial API. Then it's just a matter of string manipulation, in the time-honored tradition of CGI functions, to deserialise the parameters into a map.

   var gadgetURL = _args()["url"];
   ...
   var urlParams = null;
   function populateURLParams() {
     if (urlParams!=null) return urlParams; // Ensures we only parse once
     urlParams = {};
     if (gadgetURL.indexOf("?")==-1) return {};
     var cgiArgs = gadgetURL.replace(/.*\?/, "");
     var pairs = cgiArgs.split("&");
     for (var i=0; i<pairs.length; i++) {
       var pairParts = pairs[i].split("=");
       urlParams[pairParts[0]] = unescape(pairParts[1]);
     }
   }