Saturday, February 12, 2011

Create a jquery plug-in : creating a jquery plug-in that can convert JSON array into table

How Do I? Create a jquery plug-in : creating a jQuery plug-in that can convert JSON array into table


Download Plug-in with Samples
Download Plug-in with Asp.net Ajax Sample

This article is about learning how to create jQuery plug-in by actually creating one. I have prepared a sample plug-in that can convert a JSON array into a table. This table is a template table already present in the page and this plug-in will get this table and insert the values of variables in the desired places whether they are in table attributes or inside td’s.

Creating a plug-in is not a big task but creating a reusable plug-in needs deep understanding and better decisions at design time so it can be real reusable component later. If you want to simple know the syntax of creating a plug-in in jQuery, jQuery website has all the information and you can check it from this link
jQuery Plug-in Authoring

However this article is about creating jQuery plug-in, it’s about doing better decision while creating a plug-in. Here are some considerations

1- Plug-in should work even without binding it to jQuery
2- Plug-in should be able to maintain its state(data) for event handling
3- Plug-in should be able to attach to as much elements as we want in a page
(That means it should be object orient rather than procedural)

I am assuming that before reading this article you arefamiliar with javascript prototype programming. But if you are not, please read this article before proceedint "Object Oriented Programming in JavaScript"

In this article I will discuss in detail about all of these aspects of a plug-in. It’s a very simple plug-in and let start building it and while on it, I will discuss the above listed points. Following is the main constructor and possible listed options of table plug-in

function Table(tbl, data)
{
    //data for head and body
    this.Body = data.Body; 
    // table object
    this.RTable = tbl;
    // template for head and body and footer
    this.BodyTemplate;


    // call back function to be called on row data bound
    this.OnRow_Bounded=data.OnRow_Bounded;

    this.GatherTemplate();
    if (this.Body != null) 
    {
      this.Create();
    }
}

This is the function that will gather the template from header/footer and body from the passed table object and this template will be used to bind data
Table.prototype.GatherTemplate = function() {

    this.BodyTemplate = $("tbody", this.RTable).html();
    $("tbody tr:first", this.RTable).remove();

}

After getting all the templates, this will save the required templates that will help in building table.
After gathering template, this next function will build the table and display it on the screen

Table.prototype.Create = function() 
{
  var i = this.CurrentPage == 0 ? 0 : this.CurrentPage * this.PageSize;

  var limit = i + this.PageSize > this.Body.length ? this.Body.length : i + this.PageSize;

  for (; i < limit; i++) 
  {
    this.RTable.append(this.CreateRow(this.BodyTemplate, this.Body[i]));
  }
            
}
This function will create a row and will optionally call a row bound function that can be used for doing different options.
Table.prototype.CreateRow = function(template, rowData) 
{

  for (var i in rowData) 
  {
    var exp = new RegExp("{" + i + "}", "g");
    template = template.replace(exp, rowData[i]);
  }
  var row = $(template);
  if (typeof OnRow_Bounded == 'function') 
  {
    row = OnRow_Bounded(rowData, row, "body");
  }
  return row;
}
Now this is a complete plug-in and when Table function will be called. It will generate a table and display it the place where the template table is placed. Now if you see that this is not a jQuery plug-in yet but it can be used as a plug-in by using it following way
  Var table=new Table($(“table:first”),{Body:yourJSONData});
What it takes it to convert it to a jQuery plug-in is very simple. 1- Initilize a default options object var options = { Head: null, Body: null, AjaxPager: false, CurrentPage: 0, TotalPages: 0, PageSize: 10, Pager: true,OnRow_Bounded:null,OnPager_Clicked:null } 2- Extend the jQuery library
$.fn.CreateTable = function(data) 
{
  //if (this.length > 0) {
  $.extend(options, data);
  var index = 0;
  var objArray = new Array();
  this.each(function() 
  {
    objArray[index] = new Table($(this), options);
    index++;
  });
  return objArray;
  //}
}
Inside this on using a each loop for all tables in the page will bind data to all tables. Default options are extended with extend jQuery object and now this is a complete jQuery plug-in that you can call using jQuery by using the following syntax
  $(“table”).CreateTable({options});
As you can see inside the each loop , a new Table object is created and it works the way it should be. About the second point, where I mentioned it should maintain its state. This plug-in will give back the array of Table objects. These objects can be used to get or set state. These objects can be used in many ways. This article does not cover the whole plug-in but it has the taste of what it is capable of. This article includes various working examples that can be downloaded from the below link. http://rapidshare.com/files/447560766/jQuery-CreateTable-PlugIn.zip

No comments:

Post a Comment