简体   繁体   中英

How do I mimic the functionality of this callback in jquery/js?

I am replacing the jQuery-ui Autocomplete library with one that I made. The old initializer for my input element looks like this:

$('#search_input').autocomplete({
   minLength: 2,
   select: function(event, ui) {
     $('.some_element').val('ui.item.id');
     return false;
   }
});

My new auto-complete library looks like this:

$.fn.custom_search = function() {
  $(this).on('keydown click', (e) function(){
  switch e.type {
    case 'keydown':
      ...
      search_term = $(this).val();
      ajax_caller(search_term);
      break;
    case 'click'
      ...
      break;
  }

};

How can I maintain the 'select' functionality from the jQuery-ui Autocomplete? I want everything passed to select in the initializer to fire upon an item being selected from the search results from my custom auto-complete.

The 'ajax_caller' function passes the search term to the controller. The controller compiles a list and returns it to a js.erb which creates a list of search term results and attaches it to the bottom of the input.

The select callback is supposed to be fired when someone chooses an option from the search term results.

You need to pass the select callback as an option into your plugin, something like this:

$.fn.custom_search = function(options) {
  options = options || {};
  var select = options.select || function() {};
  $(this).on('keydown click', (e) function(){
  switch e.type {
    case 'keydown':
      ...
      search_term = $(this).val();
      select($(this), search_term);
      ...
  }

};

And then you will pass it like for jQuery autocomplete:

$('#search_input').custom_search({
   select: function(element, value) {
     $('.some_element').val('ui.item.id');
     return false;
   }
});

Also check this jQuery plugin template , and you can find more similar templates to help you writing a well-structured plugin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM