Refactored to prevent event callback recursion and crash.