Refactor event handler code