O'Reilly logo

Programming Social Applications by Jonathan LeBlanc

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Different Approach to Markup and Data

As we’ve just discussed, OpenSocial templating is a different approach for handling the visualization of data sources. Let’s take a practical look at what this means. Let’s assume that we have set up a data request that captures user profile information, and that source returns a JSON structure with the viewer’s profile details:

var userData = {
   name: "John Smith",
   gender: "Male",
   thumbnailUrl: "http://www.johnsmith.com/img/profile.jpg",
   profileUrl: "http://www.container.com/johnsmith"
}

Now that we have a data source, we want to use it to build out a user badge. We have a few options for how we can do this, which we’ll cover next.

Dynamically creating the DOM nodes

One approach that is used frequently within the context of gadget construction is to create any required DOM nodes dynamically within the JavaScript layer. This means that all styles, content, and node sources are built using the node property setters:

<div id="profile"></div> <script type="text/javascript"> var profileNode = document.getElementById("profile"); //build profile image var imgThumb = document.createElement("img"); imgThumb.src = userData.thumbnailUrl; imgThumb.setAttribute("style", "float:left; margin-right:10px;"); profileNode.appendChild(imgThumb); //build profile content text node var spanProfile = document.createElement("span"); spanProfile.innerHTML = "Name: " + userData.name + "<br />Gender: " + userData.gender + "<br />Profile: "; profileNode.appendChild(spanProfile); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required