0

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

前任:$('#test').tabs('destroy')

4

1 回答 1

3

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

这是小部件工厂第 188 行的摘录:

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)。选项卡小部件第 466 行的摘录如下所示:

_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;
},
于 2011-04-26T07:00:55.147 回答