Refactor and improve event handling.