Refactor app.js and make event handling logic self-contained