Click here to Skip to main content
15,886,833 members
Articles / Web Development / HTML
Article

Javascript Dataset, Data Repeater and Grid

Rate me:
Please Sign up or sign in to vote.
4.25/5 (12 votes)
31 Oct 2008CPOL5 min read 61.5K   603   34   9
An object that can repeat data in any template
Javascript Grid

Introduction

When I develop Ajax based applications, I have one major problem. It is repeating data. I need to repeat data and build it every time in a different template. Sometimes, I need a grid and sometimes I just repeat rows in DIV for free layouts.

For this, first I develop an object called "JS Dataset". When you give data to the object, it can repeat it with your template. It is possible to change the dataset template in memory to use different templates based on user action.

How Dataset Template Works?

It is easy to define a template for repeat data. You need a template where each section of the template must be in an HTML comment tag. For example, each template must have "ROW" template that repeats. You need to place your template between <!--row--> and <!--end-row-->. Dataset will repeat content between these tags.

Next is how we place our data in a row, for example, where and how to tell the dataset to place Data Variables? For this, in ROW template, you need to place a SPECIAL word with this format eval/Column/ that Column is the name of the object in your data.

Confusing? Just see one example below that is a simple template with a list of objects that has column names: "id", "name", "link":

HTML
<div id="simpleTemplate">
<!--row-->
<a id="link_eval/id/" href="eval/link/" title="eval/name/">eval/name/</a>
<!--end-row-->
</div>

When you repeat sample data with the above template, the result will be:

HTML
<div id="simpleTemplate">
<a id="link_0" href="news.aspx" title="News">News</a>
<a id="link_1" href="about.aspx" title="About us">About us</a>
</div>

Now I finished showing you how to use the Template. Next is how to work with codes. There is a special parameter that is always set to the current item index in a row template - it is dataset/index/. If you put it in row template, anywhere your place it, it will replace with Index of row.

Using the Code

Before using JavaScript codes, you need to design your template. Consider columns in your data. Dataset can load the following section from template:

  • Header: Header content [Optional]
  • Row: Content to repeat for each item in dataset
  • RowAlt: Alternative template for even row index link : 1,3,5,... [Optional]
  • Footer: Footer content [Optional]
  • Empty: When no data is in dataset
  • Loading: When dataset gets data from server, show this template [Optional]
  • SortAsc and SortDesc: If dataset sorts parameter set in Header template will replace to show columns that need sorting. For example, this can be images for Asc image with up-arrow and for Desc with down-arrow. They are used in Pager object. Pager is my plug-in for this dataset.

When dataset repeats data and finishes it if footer and header exist, the result of repeats will plus with header and footer. When you design your template, now there are two ways to set it for dataset: Dynamic and Static.

Dynamic means you set the template using JavaScript and Static means that you place template in DIV tag where the result will show.

1 - Static

Place your template in DIV tag and set ID of this tag. Then use this code to load:

JavaScript
var ds = new dataset('id_of_div');
window.onload = function(){
	//Get data from server
	ds.setData(sampleData);
	ds.build();
}

Note that for this example, I use window.onload. This is because for accessing DOM objects, we need to use it when page load finishes. Then note that you need your algorithm for getting data from server like jQuery.ajax or another method like ASP.NET Web service and Microsoft-Ajax, and then set data for dataset. Last call build() method to show the result. 

An example of full template is as follows:

HTML
<div id="id_of_div">
<!--header--><div class="news-list"><!--end-header-->
<!--row--><div class="news-box-a">eval/NewsTitle</div><!--end-row-->
<!--altrow--><div class="news-box-b">eval/NewsTitle</div><!--end-altrow-->
<!--footer--></div><!--end-footer-->
<!--empty--><div class="alert">No news found, try another search</div><!--end-empty-->
<!--loading--><div class="alert">Updating...</div><!--end-loading-->
</div>

One thing that makes it easy to use this method for template is that you can see your preview of template without any problem with any software like "Microsoft Expression" or "Dreamweaver" or any other editor and it is easy to change and also see it in your browser like Chrome, Internet Explorer, Firefox or translate to any language because templates are within HTML page, If you are using ASP.NET, it is easy to localize a template without any problem with Visual Studio.

2 - Dynamic

Sometimes, we need to change a template dynamically. For example, if this is a window in your Windows Explorer. You can change the view of items to "Details, Thumbnail, Tile, Icon or List". You can now do this by using multi-theme and load them based on your algorithm.

Windows Explorer Multi View

To approach this, just use dataset.setTemplate in your new template. You can hide your template in HTML or JavaScript codes or get it from the server. In the next example, I do not load template from DIV tag, I load it from server and put it to a variable.

JavaScript
var ds = new dataset('id_of_target_div');
ds.setTemplate(sampleNewTemplate);
ds.build();

Now it is easy to switch between templates.

If you see in the first image, you see that I use Toolbar at the bottom and top of grid. Grid repeats the width of this dataset but toolbars are another object that I named as dsPager. Because dsPager is a plug-in that I wrote for my own propose, I do not describe it.

Some things that you need to know are:

  1. If you use loading template, you can call startLoading() and endLoading() to show and hide loading template.
  2. If you need to override and add more control over rendering items, just override renderItem(index, item) method. renderItem method has two parameters: the first is the index of item and the next is a data item in index position. This function by default runs getTemplate(index,item) and returns it, but sometime we need to add something after or before each row template based on index. You can override to achieve this.
  3. If you need to override and add more control over the rendering header, just override renderHeader(). renderHeader does not have any parameters. By default, it returns getHeaderTemplate(). But sometimes, we need to change the header and add something else to the header.

Samples of Override Methods

[*] Override renderItem method to add an empty DIV after every two rows:

JavaScript
var ds = new dataset('sample');
ds.renderItem = function(index, item){
	var tmp = this.getTemplate(index,item);
	if( (index % 2) == 0 && index > 0){
		tmp += '<div class="clearBoth"></div>';
	}
	return tmp;
}

[*] Override header template to add my own method for sorting items:

JavaScript
ds.renderHeader = function() {
	var tmp = this.getHeaderTemplate();
	if (this.headerSort) {
		var regex = new RegExp('eval/sort-(\\w*)/');
		var result;
		while (regex.test(tmp)) {
			result = regex.exec(tmp);
			tmp = tmp.replace(regex,
				"javascript:" + this.pagerName
				+ ".sort('" + result[1] + "')");
		};
	};
	return tmp;
};

In the above example, I use variables like "eval/sort-colA" , "eval/sort-col2", etc. With this function, I will find them and replace them with "javascript:dsPager.sort('colA')" , ...

You can develop your own method for paging and sorting in grid and list.

Be creative!

Have any ideas or comments? Do not forget to rate this article and leave comments.

History

  • 28/10/2008 First CodeProject release
  • 24/10/2008 Wrote dsPager for dataset repeat and sort function plug-in for dataset
  • 21/10/2008 Removed some bugs from first dataset object
  • 19/10/2008 First idea

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Raahbar co.
Iran (Islamic Republic of) Iran (Islamic Republic of)
I am web developer and .net programmer focusing on Asp.net MVC and Webforms development.

Comments and Discussions

 
GeneralMy vote of 5 Pin
lovejun10-Jan-11 18:27
lovejun10-Jan-11 18:27 
GeneralMy vote of 1 Pin
sachinpuri_103717-Sep-10 1:43
sachinpuri_103717-Sep-10 1:43 
Generalتشکر Pin
bachebahal_136312-Jun-09 12:08
bachebahal_136312-Jun-09 12:08 
Generaloverrided the getTemplate method repeat the data of the Child-Object Pin
Du Wei16-Feb-09 4:35
Du Wei16-Feb-09 4:35 
GeneralReally nice! Pin
laverrod3-Nov-08 23:17
laverrod3-Nov-08 23:17 
Generalgreat paper Pin
Ardavan Sharifi1-Nov-08 23:00
Ardavan Sharifi1-Nov-08 23:00 
QuestionThat's so cool Pin
barbod_blue31-Oct-08 18:22
barbod_blue31-Oct-08 18:22 
AnswerRe: That's so cool Pin
Mahdi Yousefi1-Nov-08 0:32
Mahdi Yousefi1-Nov-08 0:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.