Heads up! This post was written 14 years ago. Some information might be outdated or may have changed since then.
Когато се налага да пиша някой плъгин за jquery използвам следния pattern за т.н quick start :) :
(function($) {
    $.pluginName = function(element, options) {
        var defaults = {
            foo: 'bar',
            onFoo: function() {}
        };
        var plugin = this;
        plugin.settings = {};
        var $element = $(element),
            element = element;
        
        plugin.init = function() {
            plugin.settings = $.extend({}, defaults, options);
            // code goes here
        };
        
        plugin.foo_public_method = function() {
            // code goes here
        };
        
        var foo_private_method = function() {
            // code goes here
        };
        
        plugin.init();
    };

    $.fn.pluginName = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('pluginName')) {
                var plugin = new $.pluginName(this, options);
                $(this).data('pluginName', plugin);
            }
        });
    }
})(jQuery);
като използването на плъгина става по следния начин:
$('#element').pluginName({'foo': 'bar'});
$('#element').data('pluginName').foo_public_method();
$('#element').data('pluginName').settings.foo;
Авторът е Stefan Gabos
Подобрена/обновена версия може да се изтегли от https://github.com/zenorocha/jquery-boilerplate/

Back to all posts