Jul 15 2009

Tree-Grid Module for liteGrid

Category: jQueryMatt @ 03:53

For those just jumping on, liteGrid is a lightweight jQuery grid plug-in that’s based on an event-driven architecture.  The core does practically nothing, but through the power of events, add-on modules can extend it with additional behavior.  In this post, I’ll explain the idea behind the event-driven architecture and modules, and I’ll show you an example that brings nice tree-grid functionality (ala jqGrid) to liteGrid in a simple, easy-to-use manner.

Improvements Since Last Time

Thanks to feedback from Rob, I was able to make a few minor change to the core to clean things up. The big thing is that row IDs are no longer classes but actual element IDs.  I have no clue what I was thinking when I made row-id a class instead of using the attribute that exists specifically for such things, but oh well.

A Little About Events

While objects in the DOM fire a variety of standard events (onclick, onkeypress, etc), jQuery makes it possible to fire custom events, making it easier to build loosely-coupled systems entirely in JavaScript.  For more about custom events, I highly recommend Douglas Neiner’s article.  It’s a doozy, but well worth the read.

So, why did I choose an event-driven architecture for liteGrid?  I wanted something that was loosely-coupled and extremely flexible.  The nice thing about this approach is that any number of add-on modules can plug in to liteGrid’s events and perform whatever actions they want.  As you’ll see, this makes it possible to do some very cool things.  Further, add-on modules themselves can publish their own events, which makes it possible to have add-ons for your add-ons. :)

Making liteGrid a tree-grid: TreeGridModule

In the last post, I showed you a simple add-on module that would zebra stripe the rows in the grid.  That’s all well-and-good, but a little simplistic.  Oh, and for those wondering why the rows are restriped in batch like that, there’s actually a really good reason (as we’re about to see): rows can be inserted inside the grid. :)

So, what’s a tree-grid?  Here’s a screenshot (snapped from jqGrid’s demonstration page):

treeGrid

The basic idea is that a row can have children.  When a parent is expanded, the child rows should be displayed immediately below it, and there should be some visual indication that the children belong to the parent.  A good tree-grid should support an arbitrary depth of nesting, though this can become a UI problem since indenting things (the most common way to denote parent-child relationships) eats up quite a bit of space.

If that sounds like it is going to be a challenge, you’re right!  How can we bring this functionality to liteGrid?  Let’s look at the module at a high level:

function TreeGridModule() {
    var base = this;

    //Called by liteGrid, this initializes the module and ties it
    //into the liteGrid plumbing.  liteGrid is the actual liteGrid
    //reference.
    base.initialize = function(liteGrid, options) {
        ...
    }

    //Callback that is invoked whenever a row has been bound in the grid.
    base.rowBound = function(event, row, dataItem, index) {
        ...
    }

    //Callback that is invoked whenever a row is collapsed. 
    base.rowCollapsed = function(parentId) {
        ...
    }

    //Used to hide children without actually changing their collapsed status.
    base.recursiveHideChildren = function(parentId) {
        ...
    }

    //Used to show children recursively.  Their collapsed status is not changed, so
    //only children that are expanded are shown.
    base.recursiveShowChildren = function(parentId) {
        ...
    }

    //Callback that is invoked whenever the expando-link is clicked.
    base.rowExpanded = function(parentId) {
        ...
    }
}
TreeGridModule.prototype.defaultOptions = {
    paddingPerLevel: 5
};

All modules must define an initialize function.  This is called by the liteGrid core to initialize the module.  Next, we have a few event handlers.  The first will be tied to liteGrid’s rowBound event.  After that, we have two special event handler that handle the user collapsing and expanding rows.  After that, we have two helper functions that take care of recursively showing/hiding a row’s children (after all, if you collapse a row that has children, and those children have children, shouldn’t they be hidden, too?).  At the very end, we add an object for default options used by TreeGridModule.  By default, we want to add 5 pixels of padding as we indent children under their parents.  As you’ll see, this default can be overriden by specifying the paddingPerLevel property on the liteGrid options.

Let’s dig in to the initialization:

base.initialize = function(liteGrid, options) {

    //Store a reference to the table, that way it can be accessed later, if needed.
    base.liteGrid = liteGrid;

    if (!("getChildData" in options.dataProvider)) {
        alert("Specified data provider is not compatible with TreeGridModule, aborting initialization.");
        return;
    }

    base.dataProvider = options.dataProvider;

    //Add a column to hold the expander.
    options.columns.splice(0, 0, { field: "Expander", header: "X" });

    //Initialize module-specific options
    base.options = $.extend({}, TreeGridModule.prototype.defaultOptions, options);

    //Register to receive rowBound events, that way we can insert the expander.
    liteGrid.$el.bind("rowBound", base.rowBound);
}

First, we grab a reference to the actual liteGrid class so that we can use it in the other functions.  Next, we inspect liteGrid’s configured data provider to make sure it is compatible with the TreeGridModule.  If the provider doesn’t support retrieving child rows, the module initialization is aborted, and liteGrid can go about its business sans-tree-grid.  For simplicities sake, we also store a reference to the configured provider.  Here’s where the magic beings.  First, a new column is added to liteGrid’s column definitions.  Recall that columns are completely decoupled from the underlying data model.  The only way we’ll have an issue is if the data model actually defines a property named “Expander”, in which case we may get strange behavior. Next, we combine TreeGridModule’s default options with liteGrid’s options.  This allows the paddingPerLevel setting to be overriden by specifying a different value when liteGrid is initialized.  Finally, we register for the one event we care about: rowBound.

Recall that rowBound is fired whenever liteGrid has finished populating a row with data and is ready to insert it into the grid.  Here’s what we’re going to do when that happens:

base.rowBound = function(event, row, dataItem, index) {

    //Only add an expander if the row has children.
    if (dataItem.HasChildren === true) {

        //Add the expander
        var expanderCell = row.find("td:first");

        //This is a div because an img won't render without a src attribute.
        var expandImage = $("<div class='expander closed' />")
                        .toggle(
                            function() { base.rowExpanded(dataItem[base.options.rowIdColumn]); },
                            function() { base.rowCollapsed(dataItem[base.options.rowIdColumn]); }
                        );

        expanderCell.append(expandImage);
    }
    //TODO: We might want to show a different icon if the row doesn't have children.
}

TreeGridModule expects the data model to define a HasChildren property, though rows that don’t have children can simply omit the value altogether.  If the row being bound does have children, we add an div (rendered as an image thanks to CSS) to the first cell in the row.  We use jQuery’s toggle event to bind to appropriate event handlers: the first click of the image expands the row, the second collapses it. 

When the expander image for a row is clicked, the rowExpanded callback is invoked.  Get ready for a screenfull of code as this is the most complicated piece of the module!

//Callback that is invoked whenever the expando-link is clicked.
base.rowExpanded = function(parentId) {

    //Grab a reference to the parent, the first row we add goes after it.
    var parent = base.liteGrid.$el.find("tr#row-id-" + parentId);

    //Change the expander image
    var parentExpander = parent.find("td:first div")
            .removeClass("closed").addClass("opened");

    //Determine if the children are already loaded. If they are, we don't need to re-retrieve them.
    if (parent.hasClass("children-loaded")) {

        //Mark the children as shown, they'll be toggled on through the recursive call.
        var children = base.liteGrid.$el.find("tr.child-of-" + parentId).removeClass("hidden").addClass("shown");
        base.recursiveShowChildren(parentId);

        return;
    }

    //Otherwise, we have to load and show the children.

    //Get the padding of the parent, we need it in order to add padding to the children.
    var expanderPadding = parseInt(parentExpander.css("margin-left"));

    //Grab the child data from the provider.
    var dataItems = base.dataProvider.getChildData(parentId);

    //This is the row we're adding the next row after.  
    var targetRow = parent;

    //Add the items to the table
    $(dataItems).each(function() {

        //We want to insert the items in order, so the target for the next
        //iteration is the newly inserted row.
        var newRow = base.liteGrid.insertRowAfter(this, targetRow);

        //Mark the row as a child of the parent
        newRow.addClass("child-of-" + parentId).addClass("shown");

        //Adjust the padding of the child's expander.  It should be more than
        //it's parent.
        newRow.find("td:first div").css("margin-left", (expanderPadding + base.options.paddingPerLevel) + "px");

        //Update target, we want the next row added to go under
        //the row that was just added.
        targetRow = newRow;
    });

    //Mark the parent's children as having been loaded.
    parent.addClass("children-loaded");
}

This handler receives the ID of the row that is being expanded.  First, we grab a reference to this row from the liteGrid reference.  Next, we change the class to indicate that it’s been expanded.  Through the magic of CSS, the image will be swapped to something more appropriate (see the example below).  So far, so simple, but here’s where things get tricky.  We might be re-expanding the row.  The child rows might already be in the table, but hidden.  We check for the marker class “children-loaded” to determine whether we just need to show the children or retrieve them from the data provider.  If the children aren’t present yet, we invoke the provider to get the data items.  We want to insert rows for these items sequentially into the grid immediately after our parent row (that’s what “targetRow” is tracking).  For each item, we simply use liteGrid’s helper method insertRowAfter to add the row.  We mark it with a special class that enables us to find who the row belongs to quickly, and we adjust the padding on the row’s expander image so that it is slightly more indented than its parent was.  Finally, we mark the parent with the “children-loaded” marker class.

What happens if the child rows are already there, but hidden?  We use the parentId value to find the rows children, mark them as shown, and then recursively decide which descendents to show:

//Used to show children recursively.  Their collapsed status is not changed, so
//only children that are expanded are shown.
base.recursiveShowChildren = function(parentId) {

    //Show the children that aren't hidden.
    var children = base.liteGrid.$el.find("tr.shown.child-of-" + parentId).show();

    if (children.length > 0) {
        //Show *their* children recursively.
        children.each(function() {
            base.recursiveShowChildren($(this).data("dataItem")[base.options.rowIdColumn]);
        });
    }
}

The recursive method actually shows all children of the row we just expanded, but note that the selector is slightly more complex now: we’re only selecting children marked with the “shown” class.  This allows us to maintain the shown/hidden state of child rows recursively.  If we didn’t do this, and you expanded/collapsed a top-level element that had expandable children, the expanded/collapsed state of the children would be lost.  Tracking state with classes makes it easy to persist state in nested parent/child scenarios. 

Alright, so now we can expand rows, how do we collapse them?  Remember that our expander image has a toggle event handler, so the second time an expander is clicked, it will trigger the rowCollapsed callback:

//Callback that is invoked whenever a row is collapsed. 
base.rowCollapsed = function(parentId) {

    //Grab a reference to the parent, the first row we add goes after it.
    var parent = base.liteGrid.$el.find("tr#row-id-" + parentId);

    //Change the expander image
    var parentExpander = parent.find("td:first div")
            .removeClass("opened").addClass("closed");

    //Hide the children, and mark them as collapsed. 
    var children = base.liteGrid.$el.find("tr.child-of-" + parentId).removeClass("shown").addClass("hidden").hide();

    //Hide the children recursively.
    base.recursiveHideChildren(parentId);
}

Again, we grab a reference to the actual row being collapsed.  We toggle the class on the expander image (remember that we’re handling the image via CSS for the sake of minimal configuration).  Next, we mark the immediate children as collapsed and hide them, then we recursively hide children of the children:

//Used to hide children without actually changing their collapsed status.
base.recursiveHideChildren = function(parentId) {

    //Hide the children, but don't mark them as collapsed.
    var children = base.liteGrid.$el.find("tr.child-of-" + parentId).hide();

    if (children.length > 0) {
        //Hide *their* children recursively.
        children.each(function() {
            base.recursiveHideChildren($(this).data("dataItem")[base.options.rowIdColumn]);
        });
    }
}
Note that we’re hiding the children without altering their shown/hidden state (which is stored as a class).  This enables to restore them to the correct state when the parent is re-expanded.

Put it all together, and you have a tree-grid.  Here’s how to use it:

//Turn #myTable into a rich table.
$("#myTable").inrad_liteGrid(
    {
        columns: [
            { field: "Name", editable: true },
            { field: "Value", header: "My Value", editable: true },
            { field: "Cost", editable: true, type: "currency" },
            { field: "Other", editable: true }
        ],
        dataProvider: new MockDataProvider(),
        modules: [new TreeGridModule(), new StripifyModule()]
    });

And here’s what it looks like:

liteGrid

I was extremely pleased with how easy it was to add this functionality on top of liteGrid.  The liteGrid core stays nice and light, and the module has a single responsibility: to make rows within the grid expandable.  In the next post, we’ll (probably) look at the inline-editing module that I’m working on now.  It’s more complex, but (so far) I’m very pleased with how clean and flexible it is. 

As always, please let me know what you think!

Tags:

Jul 13 2009

Introducing liteGrid, a lightweight jQuery grid plug-in

Category: JavaScript | jQueryMatt @ 04:49

At my day job, we’re basically stuck re-implementing Excel in a web environment.  (Sidenote: Rob tells me that this is absolutely the correct way to build applications and all web applications should try to mimic desktop applications as much as possible.  I don’t like it, but it’s the cards we’ve been dealt, and we have to make it work.)  Right now, we’re using jqGrid with ASP.NET MVC, and we’ve got things working at a rudimentary level. However, we’ve found ourselves tripping more and more over jqGrid bugs, limitations, and just plain *pain* when trying to extend it.  My take on jqGrid is that it’s too heavy to be flexible, plus it’s not a perfect match for what we’re trying to build in this application.  It’s actually becoming a barrier to progress.  Though there are alternatives, there is nothing that we’ve found that has all the functionality we need.  So, I have now been tasked with creating a new plug-in from scratch that is flexible enough to support our needs.  I have dubbed this effort liteGrid (the name sucks because there are 10,000 table plug-ins, and all the good names have been taken).

First, here the requirements I laid out for myself as I built liteGrid.  Some of these are based on application needs, but many are just based on design principles that I felt were important:

  • Must support tree-grid functionality.  You should be able to expand and collapse rows.
  • Must support flexible editing.  Items in the grid should be editable, and it should be very clean and easy to customize how things are edited.
  • Easy to customize.  If you want to change something on the grid, it should be easy and straightforward.
  • Easy to handle formatting.  You should have complete control over how values are rendered.
  • Completely decoupled data model.  The underlying data model should be distinct from what’s rendered.
  • AJAX support.  At a minimum, loading and saving data should be doable with AJAX.
  • Simple.  The grid itself should contain very little code.
  • Event-driven.  The grid should be loosely-coupled and use events to pass messages.  I was inspired by this article on custom events in jQuery.
  • jQuery UI support.  I hate coming up with themes for anything as I have no artistic inclination (at all), so this is me passing the buck. I’m still not sure how feasible this is as I’m a complete newb on jQuery UI, but hopefully they have something I can leverage.

Before we go any further …

DISCLAIMER

I do not consider myself to be a JavaScript or jQuery guru (yet).  This is also a work in-progress. I fully expect it to undergo major changes as additional functionality is added.  I’m not claiming (yet) that it’s the best grid out there, just that I like the way it is shaping up.  Still, all feedback is welcomed at this point, so feel free to throw rocks at it.  Oh, and this may/may not eventually be released in final form.  It depends on how my employer wants to handle it.  This code is not free and open-source yet, so read it at your own risk (though I really don’t think anyone is going to care). 

Getting Started

There is a “right” way to build a jQuery plug-in.  And this is it.  I used Starter to generate my skeleton plug-in, which saved me quite a bit of time.  From there, I modeled the core of liteGrid based loosely on how ASP.NET data grids work.  The grid raises events when certain things happen, which interested parties can then listen for and respond to.  I wanted to keep the core extremely simple and light, so I also built in support for pluggable modules that hook into the grid to provide additional functionality.  The tree-grid, which I’ll show in a future post, is implemented a liteGrid module.  Also, liteGrid supports a data provider model.  By default, it uses a null provider that returns no data, but you can drop in any objection you want to serve as the provider.  By default, liteGrid requires only a single provider method, but as you will see in future posts, liteGrid modules may add additional data provider requirements.

Alright, so code time.  Let’s look at the plug-in as a whole before we dive in to the interesting methods:

(function($) {

    // Declare namespace if not already defined
    if (!$.inrad) {
        $.inrad = new Object();
    }

    //This is the actual liteGrid plug-in class.
    $.inrad.liteGrid = function(el, options) {
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;

        // Add a reverse reference to the DOM object
        base.$el.data("inrad.liteGrid", base);

        //This actually performs the initialization.
        base.init = function() {
            ...
        }

        //Rendes the actual table.  This can be overriden by modules.
        base.render = function() {
            ...
        }

        //Renders the specified row.
        base.renderRow = function(dataItem, index) {
            ...
        }

        //Builds a row that can be inserted into the table.  columnBound
        //events are raised, and the formatter is used to format cell
        //values.
        base.buildRow = function(dataItem) {
            ...
        }

        //Inserts a row for a data item after the specified row
        //that's already in the table.
        base.insertRowAfter = function(dataItem, existingRow) {
            ...
        }

        base.init();
    }


    $.inrad.liteGrid.defaultOptions = {
        columns: [],
        dataProvider: new NullDataProvider(),
        modules: [],
        missingValue: "",
        rowIdColumn: "ID"
    }


    // This is the actual plug-in function.  It creates and returns
    // a new instance of the plug-in.  
    $.fn.inrad_liteGrid = function(options) {
        return this.each(function() {
            (new $.inrad.liteGrid(this, options));
        });
    }

    // This function breaks the chain, but returns
    // the inrad.liteGrid if it has been attached to the object.
    $.fn.getinrad_liteGrid = function() {
        return this.data("inrad.liteGrid");
    }

})(jQuery);

Aside from the JavaScript added by jQuery Starter, there’s not really much going on.  liteGrid is a simple object with only a few methods: init, render, renderRow, buildRow, and insertRowAfter.  I expect this list to grow a little bit as I find common functionality that feels like it belongs on the core object, but still, this is far from a complicated object. 

Let’s look at the options that are supported right now: columns, dataProvider, modules, missingValue, and rowIdColumn.  Columns is simply an array of objects that defines the columns to be rendered.  Note that modules can modify this definition to add new columns as needed, as we’ll see in the tree-grid module.  Next is the data provider.  By default, this is a null provider that just returns an empty array.  Users of liteGrid should supply their own provider or use one of the available providers that will “ship” when this thing is finished (including an AJAX provider).  Next is the array of add-on modules for the grid.  These are initialized by liteGrid and can do all sorts of crazy things.  Next we have the value to substitute for rows that are missing a value for a column.  This may be a bit of YAGNI creeping in, so I might remove it later.  Finally, we have the name of the column (we’re talking data model column) that contains the unique identifier for the row.  This should probably renamed to “rowIdProperty” for clarity.  Basically, the underlying data objects that are returned by the grid’s data provider must expose a unique identifier, and this is the name of that identifier.

Alright, time for some code.  Let’s dig in to the init method first:

base.init = function() {

    base.options = $.extend({}, $.inrad.liteGrid.defaultOptions, options);

    //Initialize all modules!  Modules might, for example, add
    //new columns (such as the expander column), add decorators to
    //the providers, subscribe to events, or do other fun things.
    $(base.options.modules).each(function() {
        console.log("Initializing %s...", this.constructor.name);
        //TODO: Add error-handling!
        this.initialize(base, base.options);

        console.log("Finished!");
    });

    base.render();
    base.$el.trigger("tableRendered");
}

There is the standard jQuery stuff for handling options.  After that, all the modules are initialized.  This is done prior to *anything* else happening because modules can do whatever they want to the grid.  They can override methods, they can change options, they can register event handlers, whatever.  Next, we render the grid, and fire a custom event on the actual table element itself that signifies that rendering is complete.  Pretty simple!

Next up is the render method:

//Rendes the actual table.  This can be overriden by modules.
base.render = function() {
    //Clear any existing table markup
    base.$el.html("");

    //Build the header.
    var headerRow = $("<tr></tr>");
    $("<thead></thead>").append(headerRow).appendTo(base.$el);

    $(base.options.columns).each(function() {
        headerRow.append("<th>" + (this.header || this.field) + "</th>");
    });

    //Grab data and add the rows.
    var dataArray = base.options.dataProvider.getData();

    $(dataArray).each(function(index) {

        base.renderRow(this, index);
    });

    //The table has been rendered, so trigger the event.
    base.$el.trigger("tableUpdated", base);
}

This method does a lot, so it defers a lot of logic to helpers where it can.  First, it wipes out any existing HTML content, and builds a header row for the table based on the column definitions.  Next, the data items are retrieved from the configured provider, and a row is rendered for each table.  Finally, an event is raised to signify that the grid has changed in some way.

Next is our helper to render a row.   I’ll also throw in a related method that builds the actual row:

//Renders the specified row.
base.renderRow = function(dataItem, index) {

    var row = base.buildRow(dataItem);

    base.$el.append(row);
}

//Builds a row that can be inserted into the table.  columnBound
//events are raised, and the formatter is used to format cell
//values.
base.buildRow = function(dataItem) {

    //Spit out values for each of the columns
    var row = $("<tr></tr>");

    //Add a class containing the ID
    row.addClass("row-id-" + dataItem[base.options.rowIdColumn]);

    //Bind the actual data item to the row so that we can get it later.
    row.data("dataItem", dataItem);

    $(base.options.columns).each(function() {
        var column = this;

        //Format the value.
        var value = (dataItem[column.field] || base.options.missingValue));

        var element = "<td>" + value + "</td>";
        element = $(element).appendTo(row);

        base.$el.trigger("columnBound", [column, element]);
    });

    //Raises the "rowBound" event on the table.
    //TODO: Can we hand the user the row's index?  Probably not...
    base.$el.trigger('rowBound', [row, dataItem]);

    return row;
}

renderRow simply calls buildRow to build up the DOM tree for the row, then appends it to the table.  buildRow is a little more complicated.  First, the new row is tagged with a special class that stores the row’s ID.  The jQuery data function is also used to store the raw dataItem with the row, making it easy to grab the raw data later.  Next, a cell is rendered for each column.  Note that the data item may define fields beyond the column specifications, it is completely flexible in this regard.  If the data item doesn’t define the column, the missing value is used instead.  When it’s all finished, an event is triggered, again on the table element, that allows interested parties to see what’s going on.

The last method our grid exposes is a helper for modules to use.  It inserts a row after an existing row in the table:

base.insertRowAfter = function(dataItem, existingRow) {

    //Create the row.
    var row = base.buildRow(dataItem);

    //Insert it.
    row.insertAfter(existingRow);

    //The table has been changed, so fire the event.
    //TODO: Do we *really* want to fire this after every insert?  Would
    //it be better to have a way to supress the event being fired, and
    //allow modules to trigger the event?
    base.$el.trigger("tableUpdated", base);

    return row;
}

It uses the buildRow function, insuring that all our events are fired, adds it to the DOM, and triggers an event indicating that the table has changed.

And that’s all there is to it!  How do we put this grid into action?  Here’s a simple example:

$(function() {
    //Subscribes to events just to make sure they work.
    $("#myTable").bind("rowBound", function() {
        //alert("Received rowBound event!");
    })
    .bind("columnBound", function(event, column, element) {
        //element.html(column.field + ": " + element.html());
    })
    .bind("tableRendered", function(event) {
        //Do some table-specific processing?
    });

    //Turn #myTable into a rich table.
    $("#myTable").inrad_liteGrid(
        {
            columns: [
                { field: "Name" },
                { field: "Value", header: "My Value" },
                { field: "Other" }
            ],
            dataProvider: new MockDataProvider(),
            modules: [new TreeGridModule(), new StripifyModule()]
        });
}
);

This tells the plug-in to convert the table with ID #myTable to a liteGrid.  We are passing in a custom data provider for testing:

function MockDataProvider() {
    this.getData = function() { 
        return [
            {ID:1, Name:"Name1", Value:"Value1", Cost:1234, HasChildren:true},
            {ID:2, Name:"Name2", Value:"Value2", Cost:12345, HasChildren:true}
        ];
    };
    
    //Gets child data from the server.
    this.getChildData = function(parentId) {
        if (parentId == 1) {
            return [
                { ID: 3, Name: "Child1", Value: "Value3", Cost: 1234, HasChildren:true },
                { ID: 4, Name: "Child2", Value: "Value4", Cost: 1234, HasChildren:false }
            ];
        }
        else if (parentId == 2) {
            return [
                { ID: 5, Name: "Child1", Value: "Value3", Cost: 1234 },
                { ID: 6, Name: "Child2", Value: "Value4", Cost: 1234 }
            ];
        }
        else if (parentId == 3) {
            return [
                { ID: 7, Name: "Child1", Value: "Value3", Cost: 1234 },
                { ID: 8, Name: "Child2", Value: "Value4", Cost: 1234 }
            ];
        }
        else { 
            return [];
        }
    }
}

Note that this provider actually has a few things that are required by the tree-grid module, which I’ll show in the next post, but liteGrid doesn’t care.  It simply looks for matches between your column definitions and the fields on your data items, and skips anything that doesn’t match.

There you have it, liteGrid.  Before I end this post, let’s look at a simple module that stripes the rows in the table:

function StripifyModule() {
    var base = this;
    
    //Registers for events that signal that the table needs to be 
    //re-stripified.
    base.initialize = function(liteGrid, options) {

        //Register for the events we care about.
        liteGrid.$el.bind("tableUpdated", function(event, table) {

            //Remove even/odd classes from everything
            table.$el.find("tbody tr").removeClass("even odd");

            table.$el.find("tbody tr:even").addClass("even");
            table.$el.find("tbody tr:odd").addClass("odd");
        });
    }
}

By simply subscribing to events, this module can now apply stripes to the table anytime a row is added or removed.  This is a very simple example, and the true power of this functionality won’t really be obvious until the next post, when I show the TreeGridModule.

Alright, so, comment away.  What do you think?  Any suggestions for improving things?

Tags: