refactored event handler code