refactor and simplify events code