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); ...

Get Programming Social Applications now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.