Fixing scope of variables in event handler function