Fix bugs, esp creating handler functions in loop

See http://jslinterrors.com/dont-make-functions-within-a-loop