2

我已经创建了一个用于自定义表单元素的 jQuery 插件......现在我想向其中添加 destroy 方法并调用它,但无法完成它。这是破坏方法,但它不能按预期工作以及我如何调用它。

该插件灵感来自 Addy Osmani 插件结构。

;( 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 );
4

0 回答 0