How to Panic Buy in Dota 2?
You can drag items from the store into your "Quick Buy" bar, the bar is located just above the inventory, as seen in the image below:
So when you have the shop open, drag the next item you are planning on buying into that bar, then each of the individual components for that item will appear in that bar (so for example, if you are building power treads boots of speed, gloves of haste, and belt of strength will appear). If you have enough gold for any of the items you will hear a clinking of coins noise once you reach that amount of gold telling you that you can now afford an item in your quick buy bar. You can then right click the items in the quick buy bar to buy them.
So if you are about to get ganked, you can quickly right click stuff in that bar, and then you don't have to worry about the lost gold. Although since the bar also makes the sound effect once you have enough gold for an item, you can make sure you never have much gold to lose anyway by always buying your items once you have enough gold for them.
If you want to clear your quick buy bar you can also just press the litte "x" located in the bottom right hand corner of the quick buy bar. And just a final note on the quick buy bar, there's also a tp scroll in the quick buy bar just above the "x" I just mentioned, that way you can quickly buy a tp scroll to teleport somewhere.
There are key-binds you can set up in the options, under the items category I believe, for Purchase Quick-Buy (as described by LagAttack) and also Purchase Sticky (which is a TP scroll by default)
I have Purchase Sticky (TP scroll) bound to space bar, so that if i get ganked and I don't have enough gold for any component of my next item, I can still spend because TP scrolls are essential and should always be carried. This also allows for some fast escapes at the side shop, I just run past and hit space and I get my escape scroll.
It is also worth mentioning that you don't need to spend ALL your gold, only the UNRELIABLE gold - which is gold from farming creeps. Gold awarded from kills, tower kills, Roshan and Hand of Midas is reliable gold, and is not lost when you die. If you mouse over your current gold it will tell you how much is reliable and how much is unreliable. The unreliable gold is always spent first.