3
\$\begingroup\$

I was having some real issues creating a jQuery plugin that could handle multiple instances with different config options. I came up with this, but am not sure if it follows best practices. I used some sample boilerplate, but it didn't handle exactly what I wanted, though the core of that still remains.

Here's a fiddle: https://jsfiddle.net/nvyxjpwu/9/

I wanted something that can be called like this:

$('#me').testPlugin();
$('#metoo').testPlugin({ backgroundColor: 'red' });
$('#methree').testPlugin({ backgroundColor: 'yellow' });

$("#me").testPlugin('makeDoThing', 35);
$("#metoo").testPlugin('makeDoThing', 50);

javascript

(function ( $ ) {

    var Plugin = function(el){

        var plugin = {};

        var config = {
            backgroundColor: 'blue'
        }

        plugin.el = el;
        var $el = $(el);
        var $elSpan;

        plugin.methods = {
            init: function(options){
                $elSpan = $el.find('span');
                $.extend(config, options);
                $el.css(config);
            },
            makeDoThing: function(size){
                $el.css({ fontSize: size+'px' });
                $elSpan.html('HELLO');
            }
        }

        return plugin;
    }

    var INSTANCES = {};

    $.fn.testPlugin = function(input){

        var EL   = this;
        var ARGS = arguments;

        this.each(function(){

            var id = $(this).attr('id');

            if(!INSTANCES[id]){
                INSTANCES[id] = new Plugin(EL);
            }

            var plugin = INSTANCES[id];

            if ( plugin.methods[input] ) {
                return plugin.methods[input].apply( plugin.el, Array.prototype.slice.call( ARGS, 1 ));
            } else if ( typeof input === 'object' || !input ) {
                plugin.methods.init(input);
            } else {
                $.error( 'Method ' +  input + ' does not exist on jQuery.narratorsGrid' );
            }
        });
    }

}(jQuery));
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.