Reorder code to improve event binding functionality (Fixes Issue #5043)