Question

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?

Was it helpful?

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

OTHER TIPS

you can check if there's an element...

 _hideInputHolder: function() {
    if ($(this._inputHolder,'body').length) {
         this._inputHolder = this._inputHolder.detach();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top