IndianGhost/liveSearch

Consider creating a jQuery plugin

Opened this issue · 1 comments

Arkni commented

Hi @IndianGhost,

Good work so far on this plugin. It seems like a good start for a good one in the future.

Although this was declared as a jQuery plugin, it still lacks the definition of one. A jQuery plugin should give a user a way for initializing it when they want and/or a way for destroying (detach it from the table) it when they feel the need for it.

By initializing above, I meant it should give a user, like me, a way to attach it to whatever table I want and use whatever filter input (search box as you describe it). It should never restrect me from using my own Ids or names.

In order to reach this, you will need to provide a way for passing some settings/options to the plugin. Below is a possible definition for this plugin:

(function($) {
  var defaultOptions = {
    // By default, this plugin will look for table with the Id "live-search-table"
    table: "#live-search-table"
  };

  function LiveSearch(options, searchInput) {
    this.options = $.extend({}, defaultOptions, options);

    this.searchInput = searchInput;

    // Init the plugin
    this.init();
  }

  $.extend(LiveSearch.prototype, {
    init: function() {
      // TODO: Attach events to the search input
    },

    destroy: function() {
      // TODO:
      //   Unbind the events and remove the plugin instance
      //   from the input
    }
  });

  $.fn.liveSearch = function(options) {
    // If nothing is selected, exit.
    if (!this.length) {
      console.warn( "Nothing selected, can't validate, returning nothing." );
      return;
    }

    // Get the search input element
    var searchInput = this[0];

    // Check if a liveSearch instance for this input was already created
    var pluginInstance = $.data(searchInput, "live_search" );
    if (pluginInstance) {
      return pluginInstance;
    }

    // Create a new instance of the plugin
    pluginInstance = new LiveSearch(options, searchInput);

    // Assign it to the search input for subsequent usage
    $.data(searchInput, "live_search", pluginInstance);

    // Finally, return the create instance
    return pluginInstance;
  };
})(jQuery);

Usage:

$("#live-search-input").liveSearch({ table: "#my-table" });

For a starter project on how to create a jQuery plugin, see: https://github.com/jquery-boilerplate/jquery-boilerplate

In case you want to have a much broader knowledge on the most used jQuery patterns in JS world, you can check this repository: https://github.com/jquery-boilerplate/jquery-patterns

You can also read this book by Addy Osmani (free to read online): https://addyosmani.com/resources/essentialjsdesignpatterns/book/

Feel free to ping me whenever you need some help.

Hope this helps and good luck with your project.

Hello @Arkni
I will read these links as soon as possible and improve this project
Thank you very much for your help ! 😄