cweston
cweston

Reputation: 11647

jQuery Templating - Associating data to template DOM elements

I am using jQuery's template plugin rendering several row items similiar to this:

var clientData = [
    { name: "Rey Bango", id: 1 },     
    { name: "Mark Goldberg", id: 2 },     
    { name: "Jen Statford", id: 3 } ]; 

<script id="clientTemplate" type="text/html">     
    <li><${name}</li> 
</script> 

$("#clientTemplate").tmpl(clientData).appendTo( "ul" ); 

I am wondering if it is possible to make use of jQuery's data function to be able to associate each row item back to an identifier for updating.

Normally you could do something like this:

$.each(clientData, function(idx, item) {
    $('<li></li>').appendTo('ul#clientTemplate')
        .text(item.name)
        .data('clientId', item.id);
});

$('ul#clientTemplate li').click(function() {
    updateClient($(this).data('clientId'));
});

However you don't have this type of control when templating.

Note: I'd rather not use new hidden elements to store this data on each row, or additional attributes on the elements if I don't have to.

Ideas?

Thanks

Upvotes: 5

Views: 803

Answers (2)

RP Niemeyer
RP Niemeyer

Reputation: 114802

The jQuery Templates plugin includes the tmplItem function that allows you to get back to the actual data associated with any element rendered by a template.

So, you would be able to do something like:

var client = $("li").first().tmplItem().data 

In this case client would be your data:

{ name: "Rey Bango", id: 1 }

Sample here: http://jsfiddle.net/rniemeyer/fvhj4/

Upvotes: 1

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

This could be a workaround:

$("#clientTemplate").tmpl(clientData).filter("li").each(function(i){
   $(this).data(clientData[i].id);
}).appendTo( "ul" ); 

Hope this helps. Cheers

Upvotes: 1

Related Questions