mikeski.net kotlin java javascript hugo development

mikeski.net development blog

JQuery Stateful Plugin

Creating a JQuery plugin (https://github.com/mikebski/demano) for filtering objects on a page, I needed a way to create a stateful JQuery plugin. This allows me to use the same plugin on a single page so I can have multiple independent filters on a page.

Make plugin “statful”

This is done by attaching all of the configuration for the plugin to the actual DOM element we create the plugin on. This allows multiple separate “instances” of the plugin on the page. The only catch is that each must be on a separate DOM entity.

## Code & JSFiddle Example

Here’s the example code:

 (function ($) {
     function clicked() {
         console.log("Clicked 2");
         console.log(this);
         console.log(this.settings);
         console.log("Done 2");
     };
 
     $.fn.ttt = function (config) {
         this.each(function () {
             var defaults = {
                 filter_class: "filter",
                 filterable_class: "filterable",
                 attribute_name: "attribute",
                 value_name: "value",
                 group_name: "group",
                 toggle_class_matched: "on",
                 toggle_class_nomatched: "off",
                 debug_element_id: null,
             };
 
             this.settings = $.extend(defaults, config);
             $(this).on("click", $.proxy(clicked, this));
         });
     };
 }(jQuery));
 

Note that we proxy the click listener so that “this” in the callback function points to the DOM element that the configuration is attached to.

Here it is on JSFiddle: https://jsfiddle.net/mbaranski/q2rarzfn/

Here is the github plugin: https://github.com/mikebski/demano/