Reputation: 15
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?
Upvotes: 0
Views: 131
Reputation: 388416
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();
}
Upvotes: 1
Reputation: 65274
you can check if there's an element...
_hideInputHolder: function() {
if ($(this._inputHolder,'body').length) {
this._inputHolder = this._inputHolder.detach();
}
}
Upvotes: 0