diff --git a/source/UI/js/Core/Focus.js b/source/UI/js/Core/Focus.js index 90fcf7b6..88d1d28c 100644 --- a/source/UI/js/Core/Focus.js +++ b/source/UI/js/Core/Focus.js @@ -9,6 +9,24 @@ Ox.Focus = (function() { var stack = [], that = { + cleanup: function() { + stack = stack.filter(function(item) { + try { + return !!Ox.$elements[item] + } catch(e) { + return false; + } + }); + }, + debug: function() { + return stack.map(function(item) { + try { + return Ox.$elements[item][0]; + } catch(e) { + return item; + } + }); + }, focusedElement: function() { return Ox.$elements[Ox.last(stack)]; }, @@ -25,9 +43,13 @@ Ox.Focus = (function() { return $element.oxid; }).concat(oxid); if ($focusedElement) { - $focusedElement - .removeClass('OxFocus') - .triggerEvent('losefocus'); + try { + $focusedElement + .removeClass('OxFocus') + .triggerEvent('losefocus'); + } catch(e) { + that.cleanup(); + } } $element .addClass('OxFocus') @@ -38,16 +60,28 @@ Ox.Focus = (function() { return Ox.last(stack) == $element.oxid; }, loseFocus: function($element) { - var index = stack.indexOf($element.oxid); + var $focusedElement, + index = stack.indexOf($element.oxid); if (index > -1 && index == stack.length - 1) { stack.pop(); - $element - .removeClass('OxFocus') - .triggerEvent('losefocus'); + try { + $element + .removeClass('OxFocus') + .triggerEvent('losefocus'); + } catch(e) { + that.cleanup(); + } + $focusedElement = that.focusedElement(); if (stack.length) { - Ox.$elements[Ox.last(stack)] - .addClass('OxFocus') - .triggerEvent('gainfocus'); + if ($focusedElement) { + try { + $focusedElement + .addClass('OxFocus') + .triggerEvent('gainfocus'); + } catch(e) { + that.cleanup(); + } + } } } },