Asynchronous template load within jQuery UI autocomplete widget

This week I was playing with jQuery UI Autocomplete widget. I usually use Mustache.js as a template engine for rendering HTML, and I load templates on-demand.

My problem was that the widget was not ready for asynchronous load.

I use this code to load the Mustache template and render it in the Autocomplete widget :


    var MustacheRender = function(TemplateName, datas, callback) {
      $.ajax({
        type: "GET",
        url: "/MustacheLoader/",
        dataType: 'html',
        data: {
          template: TemplateName
        },
        success: function(template){
          return callback(Mustache.render(template, datas));
        }
      });
    };

    $('input').autocomplete()
      .data( "autocomplete" )._renderItem = function( ul, item ) {

        var LoadAndRender = function(datas){
          $(datas).data( "item.autocomplete", item ).appendTo( ul );
        };

        MustacheRender('List-Item', item, LoadAndRender);
        return;
      };

In this case, everything is visually ok, but it does not work as expected. If you try it, you will find out that mouse* or key-based events are not triggered.
This is because the item list has not been “refreshed”.

As a workaround, you can manually refresh the list by adding this to the “LoadAndRender” callback:

$('input').data( "autocomplete" ).menu.refresh();

It now perfectly works !