views:

28

answers:

2

I'm using the plugin jquery-tmpl. Is there a way to specify a callback after a template is run? I want to do something like

<script id='itemTemplate' type='text/html'>
  <li class="item" id=${timestampMs}>
    <span class="content">${content}</span> 
  </li>
  ${processItem($('#' + timestampMs))}
</script>

Where processItem does something to the <li> element that just got generated. As it's written, though, the element doesn't exist at the time processItem is called.

Here's how I run the template:

// Make the AJAX call to the service
$.ajax({
  dataType: "json",
  url: "/getItems",
  success: function(data) {
    // fill out template from json
    $('#itemTemplate').tmpl(data).appendTo('#container');
  }
});

Thanks!

A: 

Here's the workaround I'm using for now:

$.ajax({
  dataType: "json",
  url: "/getItems",
  success: function(data) {
    // fill out template from json
    $('#itemTemplate').tmpl(data).appendTo('#container');

    // now process the new events
    $('#container .item').each(function (index) {                           
      processItem($(this))
    });                     
  }
});
yayitswei
A: 

After you call .tmpl, you have nodes that you can act upon, so you can do this:

$.ajax({
  dataType: "json",
  url: "/getItems",
  success: function(data) {
    // fill out template from json
    $('#itemTemplate').tmpl(data).each(function (index) {                           
      processItem($(this))
    }).appendTo('#container');               
  }
});

That's similar to your workaround, but you shouldn't need to reselect the items, and you should be able to chain the call.

jrduncans