Friday, February 10, 2012

jQuery Plugins (Non-jQuery UI Version)

I was (and still am) a fan of the jQuery UI widget template system (src1, src2, lmgtfy) for creating modular UI functionality. But if you're not a fan of the overhead of including the jQuery UI libraries, you can create the same effect with just plain 'ol jQuery plugins. You don't get all the bells and whistles of the widget factory, but as you can see, the set up is still very straightforward.

(function ($) {

    var settings = {
        // ...
    };

    function _private(options) {
    }

    var methods = { //public methods
        init: function (options) {
            $.extend(settings, options || {});
            return this..each(function () {
                // ...
                // use settings
                // ...
                // call _private
                // ...
            });
        },
        destroy: function () {
            // ...
            // unbind events, remove DOM objects, etc
            // ...
        },
        f1: function (args) {
            // ...
        },
        // ...
        fN: function (args) {
            // ...
        }
    };

    $.fn.pluginName = function (optionsOrMethod) {
        if (methods[optionsOrMethod]) {
            return methods[optionsOrMethod].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof optionsOrMethod === 'object' || !optionsOrMethod) {
            return _init.apply(this, arguments);
        } else {
            $.error('Method [' + optionsOrMethod + '] does not exist');
        }
    };

})(jQuery);

No comments:

Post a Comment