Rearrange some custom events code and add comments