Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 724
cweston Avatar asked Nov 04 '22 22:11

cweston


2 Answers

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/

like image 191
RP Niemeyer Avatar answered Nov 12 '22 16:11

RP Niemeyer


This could be a workaround:

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

Hope this helps. Cheers

like image 33
Edgar Villegas Alvarado Avatar answered Nov 12 '22 16:11

Edgar Villegas Alvarado