Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between jQuery autocomplete renderItem and renderItemData

Tags:

jquery

I'm trying to understand the difference between renderItem and renderItemData.

I could not find relevant documentation about this.

I have following code:

$.widget( "custom.catcomplete", $.ui.autocomplete, {
  _renderMenu: function( ul, items ) {
    var that = this,
    currentCategory = "";
    $.each( items, function( index, item ) {
      if ( item.category != currentCategory ) {
        ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
        currentCategory = item.category;
      }
      // with following code, when an element is selected
      // in menu list, the corresponding value appears in searchbox
      that._renderItemData( ul, item );
      // with following code, when an element is selected
      // in menu list, the corresponding value does NOT appear in searchbox
      // I override renderItem below
      **// that._renderItem( ul, item );**

    });
  }
});

function  handleSearchBox() {

  var data = [
    { label: "JAMES", category: "PEOPLE" },
  ];

  $( "#search" ).catcomplete({
    delay: 0,
    source: data,
    select: function(event, ui) {
      event.preventDefault();
      str = JSON.stringify(ui)
      // with renderItemData, str = item in source data
      // with renderItem str = {}
      alert(str)
      var selectedObj = ui.item.label
      $("#search").val(selectedObj);
    }
  });
 $("#search").data("custom-catcomplete")._renderItem = function(ul, item) {
                return $("<li></li>").data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
            }; 

}

My objective is to custom style menu li items. I am not sure where I am going wrong.

like image 850
GJain Avatar asked Sep 07 '13 18:09

GJain


1 Answers

renderItem builds the actual list item (<li>) that is to be appended to the result list

renderItemData is just a wrapper method that calls renderItem and stores the associated data (label and value) to the created element. This data is later used when navigating and selecting and option from the suggestion box.

You'll find that the source code for both is pretty simple:

_renderItemData: function( ul, item ) {
    return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},

_renderItem: function( ul, item ) {
    return $( "<li>" )
        .append( $( "<a>" ).text( item.label ) )
        .appendTo( ul );
},

And you should note that _renderMenu actually calls on _renderItemData:

_renderMenu: function( ul, items ) {
    var that = this;
    $.each( items, function( index, item ) {
        that._renderItemData( ul, item );
    });
},
like image 166
omma2289 Avatar answered Oct 24 '22 18:10

omma2289