jQuery

As I already told, I’m doing my tests within the Eclipse based Aptana IDE.
During creating the project, you can already decide which Javascript libraries to use (I chose jQuery).

My use case: Filtering the rows of a big HTML table on client side. Of course, this usually calls for a database driven solution, but as a matter of fact I wanted to support the filtering even in offline situations.

Preparing the HTML file

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="myFilter.js"></script>
<title>My HTML page with client side filtering</title>
...
</html>

myFilter.js

Within myFilter.js we can define our own user functions. By the way: I really love object orientated development – but this time is not the day of OO. So please don’t be disappointed if you’ll see classic procedural style in this blog entry. Maybe some day I’ll find out how to do nice and lean OO within Javascript. 😉

There’s one special callback function that is called from jQuery core after the page has completed loading:

$(document).ready(function(...){});

Within this anonymous method, all the magic is taking place. Within there we’ll even define our own methods, such as

filterTable = function()
{
   //your code goes here
}

Selectors

One of the base concepts of jQuery (next to Chaining) are Selectors. With selectors one defines the subset of the DOM that you want to manipulate, e.g.:

$('#traceTable > tbody > tr')

Selects all rows of the HTML table with the id=’traceTable’.

Chaining

A typical jQuery command is chained. That means that a method call to a jQuery object returns another jQuery object. This may look a  bit weird at first glance, but it’s quite comparable to piping in Unix environments, e.g.:

$('#traceTable > tbody > tr').each(function (i) //execute the function for all <tr> elements of tbody in #traceTable
{
   filterRow($(this), filterText);
});

What you can see here is a combination of several techniques. Both the selector $(‘…’) and the each() function are returning objects of type jQuery. Within each() an anonymous function is called for every element of the selector. Note: In the context of each() there’s also a context change of $(this). It references to the currently traversed element of the selector!

Comments are closed.