Event driven finite state machine in JavaScript