Tuesday, September 4, 2007

Javascript Object Literal

- Use object literals as flexible function parameters

Object literals are objects defined using braces ({}) that contain a set of comma separated key value pairs much like a map in Java.


{key1: "stringValue", key2: 2, key3: ['blue','green','yellow']}

The example above shows an object literal which contains a string, number, and array of strings. As you may imagine object literals are very handy in that they can be used as generic for passing in arguments to a function. The function signature does not change if you choose to require more properties in a function. Consider using object literal as the parameters for methods.

function doSearch(serviceURL, srcElement, targetDiv) {
var params = {service: serviceURL, method: "get", type: "text/xml"};
makeAJAXCall(params);
}


function makeAJAXCall(params) {
var serviceURL = params.service;
...
}

Also note that with object literals you can pass anonymous functions as may be seen in the following example:

function doSearch() {
makeAJAXCall({serviceURL: "foo",
method: "get",
type: "text/xml",
callback: function(){alert('call done');}
});
}

function makeAJAXCall(params) {
var req = // getAJAX request;
req.open(params.serviceURL, params.method, true);
req.onreadystatechange = params.callback;
...
}


Object literals should not be confused with JSON which has similar syntax. JSON is a subset of object literal notation of javascript.


self.dashboards = {
"/admin/license/installLicense.action" : "system:administration_setupsupport.3",
"/admin/agent/listAgents.action" : "system:administration_agents.5"
}

*** when needed, say there is '/' or space character, we can use double quote to escape it.

No comments: