Question

$("selector").autocomplete({ ... }).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
        .appendTo( ul );
};

from here

What is this bit doing .data( "autocomplete" ) I though data was used to attach key value pairs to dom elements as part of data-foo attribute. But that doesn't seem the case here ?

Was it helpful?

Solution

As per the documentation :

  • .data(name, value) is the setter : it attaches value to the name key
  • .data(name) is the getter : it returns the value attached to the name key

In this case, the value is an object (which stores data about the autocomplete instance bound to the node), and this object is modified in place.

It is a common pattern in the jQuery library to have a function trigger different actions depending on its arguments :

  • $(selector).click(myFunction) binds a handler to the nodes, $(selector).click() triggers the click event
  • in jquery-ui, $sel.widget('option', name, value) will generally allow you to change an option after a widget has been created, $sel.widget('option', name ) will allow you to get the value
  • etc ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top