toJS fixes from @paglias, ready to merge

Replaces #833. Fixes #577 and #251.