jQuery 플러그인 만들기 2

jQuery 플러그인 만들기

Usage

(function($) {
    $('#sample').PLUGINNAME();
}(jQuery));

Example

/**
 * PLUGIN_NAME
 * Version: VERSION
 * URL: URL
 * Description: DESCRIPTION
 * Requires: JQUERY_VERSION, OTHER_PLUGIN(S), ETC.
 * Author: AUTHOR (AUTHOR_URL)
 * Copyright: Copyright 2013 YOUR_NAME
 * License: LICENSE_INFO
 */
(function($){

    var pluginName = 'PLUGINNAME';

    var defaults = {
        pjax    : true
    };

    function Plugin(element, options){

        this.element = element;
        this.settings = $.extend(true, {}, defaults, options);
        this.onInitialized();
        this.reInitialized();
        // this.destroy();
    }

    /**
     * onInitialized
     */
    Plugin.prototype.onInitialized = function(){

        // var
        var plugin     = this,
            opts       = plugin.settings,
            element    = plugin.element,
            $element   = $(element);

        if ( ! $element.length ) return;

        // ...

        // Event Handler: Click
        $element.on( 'click', function( event ){

            // 'event' is null or not an object
            event = event || window.event;
            event.preventDefault();

            return false;
        });

    };

    /**
     * Reinitializing plugins/widget on new page content
     */
    Plugin.prototype.reInitialized = function(){

        var plugin     = this;
            opts       = plugin.settings,
            element    = plugin.element,
            $element   = $(element),
            pjax       = opts.pjax;

        if ( ! $element.length ) return;
        if ( pjax === false ) return;

        $(document).on('pjax:end', function(event) {
            plugin.onInitialized();
        });

    }

    /**
     * Destroy
     */
    Plugin.prototype.destroy = function(){

        // ...

    };

    $.fn[pluginName] = function(settings){
        return this.each(function(){
            if( !$.data(this, pluginName) ){
                $.data(this, pluginName, new Plugin(this, settings));
            }
        });
    };

    // Private function
    var privateFunction = function(){
        // ...
    };

}(jQuery));

Reference

Scroll to Top