jQuery plugin creation and public facing methods

sygad1 picture sygad1 · Oct 14, 2012 · Viewed 7.1k times · Source

I have created a plugin to convert an HTML select box into a custom drop down using DIV's.

All works well, but i'd like to make it a little better. see my jsFiddle

At the end of the plugin I have 2 methods, slideDownOptions & slideUpOptions, I would like to make these available outside of the plugin so other events can trigger the action.

Im getting a little confused how to do this and more specifically how to call the methods from both within the plugin AND from outside of the plugin.

Any help always appreciated

Answer

Inferpse picture Inferpse · Oct 14, 2012

Think about refactoring your plugin using object oriented code. With this you can make API for your plugins like jQuery UI API. So you could access to plugin methods like:

$('select').customSelect(); // apply plugin to elements
$('select').customSelect('resetOpacity'); // call method resetOpacity();
$('select').customSelect('setOpacity', 0.5); // call method with arguments

Basic template for creating such plugins will look like following:

// plugin example
(function($){
    // custom select class
    function CustomSelect(item, options) {
        this.options = $.extend({
            foo: 'bar'
        }, options);
        this.item = $(item);
        this.init();
    }
    CustomSelect.prototype = {
        init: function() {
            this.item.css({opacity:0.5});
        },
        resetOpacity: function() {
            this.setOpacity('');
        },
        setOpacity: function(opacity) {
            this.item.css({opacity:opacity});
        }
    }

    // jQuery plugin interface
    $.fn.customSelect = function(opt) {
        // slice arguments to leave only arguments after function name
        var args = Array.prototype.slice.call(arguments, 1);
        return this.each(function() {
            var item = $(this), instance = item.data('CustomSelect');
            if(!instance) {
                // create plugin instance and save it in data
                item.data('CustomSelect', new CustomSelect(this, opt));
            } else {
                // if instance already created call method
                if(typeof opt === 'string') {
                    instance[opt].apply(instance, args);
                }
            }
        });
    }

}(jQuery));

// plugin testing
$('select').customSelect();

Working JS fiddle here: http://jsfiddle.net/XsZ3Z/