Search code examples
jqueryjquery-plugins

jQuery Plugin Skeleton


Looking at jQuery's Plugins/Authoring documentation I find some questions. I need to create a plugin that lets me do the following:

$('#one').plug({foo:'bar'});
$('#two').plug();

According to the docs I should:

(function($){

    var settings = {
        foo:''
    };
    var methods = {
        init:function(options){
            return this.each(function(){
                $.extend(settings, options);

                //------ Problem ----------//
                alert(settings.foo);

            });
        }
    };
    $.fn.plug = function(method){
        //...
    }

})(jQuery);

Problem : $('#one').plug({foo:'bar'}); alerts "bar" as expected but the next line doesn't return an empty string it return "bar" too.


Solution

  • Thought I should post this out for anyone with the same question. There are many ways to create a jQuery plugin. The one I now use frequently is a this skeleton:

    (function($, window, document, undefined){
    
        function Skeleton(element, options){
            this.$element = $(element);
            this.options = options;
    
            // Plugin init goes here...
    
        }
    
        Skeleton.prototype = {
            // Plugin methods
            sampleMethod: function(){
                // ...
            }
    
        };
        // Plugin Definition //
        $.fn.skeleton = function(options){
            if( typeof options == 'string'){
                var plugin = this.data('skeleton');
                if(plugin){
                    var r = plugin[options].apply(plugin, Array.prototype.slice.call( arguments, 1 ) );
                    if(r) return r
                }
                return this
            }
    
            options = $.extend({}, $.fn.skeleton.defaults, options);
    
            return this.each(function(){
                var plugin = $.data(this, 'skeleton');
                if( ! plugin ){
                    plugin = new Skeleton(this, options);
                    $.data(this, 'skeleton', plugin);
                }
            });
        };
        $.fn.skeleton.defaults = {
            // Plugin options ...
        };
    
    })(jQuery, window, document);