Search code examples
jqueryuser-interfacewidgetdetach

How to prevent .detach from trying to .detach elements that don't exist in the DOM


Context – jQuery widget factory, rendering elements and storing them in private variables.

_renderInputHolder: function () {

    var self = this;

    this._inputHolder = $(document.createElement('div'))
        .on('focusout', function (e) {
        self._hideInputHolder.apply(self, [e]);
    });

},

_renderTextInput: function () {

    var self = this;

    this._textInput = $(document.createElement('input'))
        .keypress(function (e) {
        if (e.which === 13) {
            self._hideInputHolder();
        }
    });
},

_hideInputHolder: function () {

    this._inputHolder = this._inputHolder.detach();

},

Problem – two separate elements have independent events that try to detach the container element. When the enter keypress occurs on the text input, it detaches the inputContainer but this also causes a 'focusout' event to be triggered on the inputContainer, resulting in a

Uncaught Error: NotFoundError: DOM Exception 8 

as it tries to detach it again.

What's the best way to ensure the inputContainer's removal without error OR check that .detach() can be called?


Solution

  • you can hold a state variable using data() to see whether the element is detached

    if(!this._inputHolder.data('detached')){
        this._inputHolder = this._inputHolder.data('detached', true).detach();
    }