Tuesday, July 15, 2008

Simple javascript repeater

Assume you want to add content to a page after it has loaded such as JSON data retrieved from the server e.g.:
var data = [{Name: 'Google', URL: 'http://www.google.com'},
{Name: 'Yahoo', URL: 'http://www.yahoo.com'},
{Name: 'LiveSearch', URL: 'http://search.live.com/'}];
This content could possibly be displayed as
<ul>
<li>Google [http://www.google.com]</li>
<li>Yahoo [http://www.yahoo.com]</li>
<li>LiveSearch [http://search.live.com/]</li>
</ul>
or perhaps
<p><a href='http://www.google.com'>Google</a></p>
<p><a href='http://www.yahoo.com'>Yahoo</a></p>
<p><a href='http://search.live.com/'>LiveSearch</a></p>
and you don't want to have to deal with that issue in the javascript function. Firstly, create an HTML template of what the contents would look like when displayed. In the template you will have to indicate the bits that would be substituted by the actual data received. In the tradition of many great javascript libraries we'll use the ${} notation where ${Name} indicates that you want the 'Name' property of the data coming in to be placed in that location.
<p> <a href='${URL}'>${Name}</a> </p>
Now that we have a template we need a javascript function that can populate it, here's one
function ParseTemplate(aryData, strTemplate) { var result = ""; for(var i = 0; i < data.length; i++){ var obj = aryData[i]; result += strTemplate.replace( /\$\{([^}]*)\}/g, function(match, group1) { return obj[group1]; } ); } return result; }
Now, whenever new data is loaded you simply need to tell the function what template you want to use and where to put the result. Here is a full code listing to try out:

No comments: