jQuery插件...如何添加destroy方法

时间:2013-10-18 14:26:08

标签: jquery

我已经创建了一个用于自定义表单元素的jQuery插件....现在我想添加destroy方法并调用它,但是无法完成它。这是破坏方法,但它没有按预期工作,我怎么称呼它。

该插件由Addy Osmani Plugin结构Insprired。

;( function ( $, window, document, undefined ) {

    var pluginName = 'yatraCustomControl',
        defaults = {
            wrapClass: 'custom-control',
            activeClass: 'ico-active',
            icoRadio: 'ico-radio',
            icoCheckbox: 'ico-checkbox'
        };

    function CustomControl( element, options ) {
        this.element = element;
        this.options = $.extend( {}, defaults, options );

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    CustomControl.prototype.init = function(){
        this.setControl();
        this.setActive();
    };

    CustomControl.prototype.setControl = function(){
        var that = $( this.element ),
            inputType = that.attr('type'),
            cssClass;

        if( inputType === 'checkbox' ) {
            cssClass = defaults.icoCheckbox;
        } if ( inputType === 'radio' ) {
            cssClass = defaults.icoRadio;
        }   

        that.wrap('<span></span>').parent().addClass(cssClass);
    };

    CustomControl.prototype.setActive = function(){
        var that = $( this.element ),
            checkType = that.is(':checkbox');       
        checkType ? this.onCheckbox() : this.onRadio()      
    };

    CustomControl.prototype.onCheckbox = function(){
        var that = $( this.element );
        that.on('change', function() {
            if ( that.is(':checked') ) {
                that.parent().addClass( defaults.activeClass );
            } else {
                that.parent().removeClass( defaults.activeClass );
            }
        });
    };

    CustomControl.prototype.onRadio = function(){
        var that = $( this.element ),
            attrName = that.prop('name');
        that.on('change', function(){
            if ( that.is(':checked') ) {
                that.parent().addClass( defaults.activeClass );
            } else {
                that.parent().removeClass( defaults.activeClass );
            }
        });
    };

    CustomControl.destroy = function(){
        this.element.removeData();
    };

    $.fn[pluginName] = function( options ){
        return this.each( function() {
            if( !$.data( this, 'plugin_' + pluginName )) {
                $.data( this, 'plugin_' + pluginName, new CustomControl ( this, options ));
            }
        });
    }

} )( jQuery, window, document );

0 个答案:

没有答案