czar85e
1/4/2014 - 12:59 AM

Jquery Plugin Template

Jquery Plugin Template

/*
 * jQuery Plugin template
 */

(function($){
                
    var instances = [],
        Plugin    = function(){},
        defaults  = {
            // default options
        };
    
    Plugin.prototype = $.extend(Plugin.prototype, {

        name: 'MyPlugin',

        initialize : function(options){
            
            var $this    = this, 
                element  = this.element;
            
            this.options = $.extend({}, defaults, options);
        },
        
        test: function($param) {
            alert($param);
        }
        
    });
    
    // helper functions
    
    /*
    function helperX() {}
    function helperY() {}
    function helperZ() {}
    */

    // Don't touch
    $.fn[Plugin.prototype.name] = function() {

        var args   = arguments;
        var method = args[0] ? args[0] : null;

        return this.each(function() {
            var element = $(this);

            if (Plugin.prototype[method] && element.data(Plugin.prototype.name) && method != 'initialize') {
                element.data(Plugin.prototype.name)[method].apply(element.data(Plugin.prototype.name), Array.prototype.slice.call(args, 1));
            } else if (!method || $.isPlainObject(method)) {
                
                var plugin = new Plugin();
                    plugin.element = element;
                
                    instances.push(plugin);
                
                    if (Plugin.prototype['initialize']) plugin.initialize.apply(plugin, args);
                    
                element.data(Plugin.prototype.name, plugin);
            } else {
                $.error('Method ' +  method + ' does not exist on jQuery.' + Plugin.prototype.name);
            }
        });
    };
})(jQuery);


// initial assign

$("#element").MyPlugin({
    //initialize options
});

// using plugin methods after assignment

$("#element").MyPlugin("test", "Hello");

// or use the object

var object = $("#element").data("MyPlugin");

object.test("Hello");