Wednesday, November 14, 2007

OpenSocial - (contd)

Second part

Now, we can go ahead and add some Javascript and use the OpenSocial library to do some basic stuff.

The intent is to prepare a Hello Viewer application. When the widget loads,it will greet the viewer with their name, which s/he has mentioned in orkut profile.

As before all HTML and Javascript content go inside the <![CDATA[ tag.
All Javascript should be inside the tag. The final code looks like this.


<script type="text/javascript">
function onLoadViewer(dataResponse) {
var viewer = dataResponse.get('viewer').getData();
var html = viewer.getDisplayName();
document.getElementById('viewer_id').innerHTML
= html;
};
function getData() {
var req = opensocial.newDataRequest();
req.add(req.newFetchPersonRequest
('VIEWER'),'viewer');
req.send(onLoadViewer);
};
_IG_RegisterOnloadHandler(getData);
</script>


This particular line tells that, the very first function that would get executed when the gadget loads would be getData()

_IG_RegisterOnloadHandler(getData);


In the getData() method, we first create an OpenSocial DataRequest Object.
Now, there are several methods provided by Google, which we can call on this. Find a list and some samples here.

In this example, I am adding a key value pair of Viewer's ID and the name.
newFetchPersonRequest() creates an item to request a profile for the specified person ID.
Now, a request is sent using
req.send(onLoadViewer);


This sends a data request to the server in order to get a data response.
Also instates that the function which will be processing the response we get from the send(), will be done within onLoadViewer() method.

Now, in the onLoadViewer() method, I collect the dataResponse object and use the getter methods available to retrieve data.

Then, the response is populated dynamically inside the placeholder <div> "viewer_id" using the innerHTML attribute.

Further, experiment with the methods available in the library.
Have fun :)

PS :Pls do post comments/queries/requests.

No comments: