Wednesday, November 30, 2011

jQTouch Dynamic Links and Event Handlers

Alright, so one of the biggest worries I had while developing the jQTouch UI for my recent app (the first app I've ever developed with jQTouch) was generating dynamic links and getting event handlers for dynamic links.

Here's the basic idea, I had a list of items that was returned from a AJAX call, and I wanted to generate a link for each of the items.

So easy enough:

jQuery.each(data, function(){
ihtml += "<li><a href='#'>" + data.item.name + "</a></li>"
}

So that generated the links which was all good. But then I came across the problem of how do I react to each link - or at least how do I handle a click of the link and figure out which link was clicked.

The way I did this was by giving the same "id" attribute to all of the links, but then I added a custom attribute called "item_id". So my link generation became:

jQuery.each(data, function(){
ihtml += ihtml += "<li><a href='#' id='itemlink' item_id='" + data.item.id + "'>" + data.item.name + "</a></li>"
}

So each link woud have the same "id", but they would have a different "item_id".

Then using the jQTouch call back events, I extracted that "item_id" when the link was clicked.

$("#itemlink").tap(function(e, info) {
loadItem($(e.target).attr("item_id"));
}

The $(e.target) essentially grabs the element that was tapped. Then you can call your standard element inspection methods on it like .attr("item_id").
And my loadItem function would be something like

function loadItem(item_id) {
/*make AJAX call using item_id */
}

So each link will react to this, but then the attr("item_id") will be different.

Hope that makes sense.

1 comment:

cli23 said...

Btw - in HTML5, the best way to do this is use "Data Attributes", so rather than item-id, use data-item-id and then using libraries like JQuery, you can query, this.data("item-id").