Move event handling into its own function