、。
I was playing baseball when a button came off.
Literal
Baseball [obj-を] was-doing-[ていた] time [at-に] button [subj-が] came-off-[explanatory-んだ].
~ていた時に ('when I was doing X') marks a past ongoing action as the temporal setting for another event. 取れる here means 'come off, come loose' (distinct from 取れる as potential of 取る 'can take'). The final ~んだ (casual of ~のだ) adds explanatory context — 'it was the case that.'