Search code examples
jqueryjquery-uijquery-ui-draggablejquery-ui-resizable

Does jQuery remove also destroy resizables/draggables?


In jQuery + jQuery UI, does calling .remove() on an element that also has resizable/draggable configured on it inherently call .resizable('destroy') + .draggable('destroy'), or an equivalent method that properly cleans everything up? Do I have to destroy the resizable/draggables before calling remove?


Solution

  • It seems like you don't need to call destroy function before calling remove. jQuery .remove triggers .destroy inherently. I could not find this documented anywhere and I was surprised to find this out.

    When including jQuery UI, the library overrides jQuery's cleanData function to include the code to trigger .remove event. (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.widget.js#L16)

    Check this demo - http://jsfiddle.net/UMYzD - the .remove handler is called when calling .remove function. Now uncheck the jQuery UI from the left pane (http://jsfiddle.net/UMYzD/1) and you would see that the .remove event handler is not triggered any more when calling .remove.

    $.cleanData = function( elems ) {
        for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
          try {
            $( elem ).triggerHandler( "remove" );
           // http://bugs.jquery.com/ticket/8235
          } catch( e ) {}
        }
        _cleanData( elems ); 
    };
    

    The line $( elem ).triggerHandler( "remove" ); triggers the .remove event bound on that element by the widget and all the way it calls the .destroy on the widget inherently.

    Below is the call hierarchy,

    enter image description here

    Below is the snapshot from fiddle http://jsfiddle.net/nxrzY/1/

    enter image description here