Added a custom event emitter and re-write the existing code to use events