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
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/
This could be a workaround:
$("#clientTemplate").tmpl(clientData).filter("li").each(function(i){
$(this).data(clientData[i].id);
}).appendTo( "ul" );
Hope this helps. Cheers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With