当我们在jQuery UI中发出destroy方法时会发生什么

时间:2011-04-26 06:58:53

标签: jquery jquery-ui widget destroy

当我们destroy jQuery ui小部件时,幕后发生了什么。

ex:$('#test').tabs('destroy')

1 个答案:

答案 0 :(得分:3)

如果你看看小部件工厂的源代码,你会注意到它会发生的事情是它会删除小部件首次初始化时添加到DOM的多余元素,类和绑定事件。简而言之,它将有效地将目标元素恢复到其原始状态。

这是摘自line 188 of the widget factory

destroy: function() {
    this._destroy();
    // we can probably remove the unbind calls in 2.0
    // all event bindings should go through this._bind()
    this.element
        .unbind( "." + this.widgetName )
        .removeData( this.widgetName );
    this.widget()
        .unbind( "." + this.widgetName )
        .removeAttr( "aria-disabled" )
        .removeClass(
            this.widgetBaseClass + "-disabled " +
            "ui-state-disabled" );

    // clean up events and states
    this.bindings.unbind( "." + this.widgetName );
    this.hoverable.removeClass( "ui-state-hover" );
    this.focusable.removeClass( "ui-state-focus" );
},

小部件通过原型化内部方法_destroy来实现自己的清理程序(这是工厂中的无操作方法,即它没有做任何事情;你可以看到它是在destroy方法的开头调用的。 line 466 of the Tabs widget摘录如下:

_destroy: function() {
    var o = this.options;

    if ( this.xhr ) {
        this.xhr.abort();
    }

    this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );

    this.list.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" );

    this.anchors.each(function() {
        var $this = $( this ).unbind( ".tabs" );
        $.each( [ "href", "load" ], function( i, prefix ) {
            $this.removeData( prefix + ".tabs" );
        });
    });

    this.lis.unbind( ".tabs" ).add( this.panels ).each(function() {
        if ( $.data( this, "destroy.tabs" ) ) {
            $( this ).remove();
        } else {
            $( this ).removeClass([
                "ui-state-default",
                "ui-corner-top",
                "ui-tabs-active",
                "ui-state-active",
                "ui-state-disabled",
                "ui-tabs-panel",
                "ui-widget-content",
                "ui-corner-bottom"
            ].join( " " ) );
        }
    });

    return this;
},