Improve event handling and make more plugin friendly