Making sure your inline script is only included once when multiple content items are listed
The sample is from our Shoutbox module in Parts.Common.Metadata.Summary-ShoutboxMessage.cshtml.
So what happens here? The WorkContext can contain a "state", i.e. key-value pairs that are only valid for the current request: if a value is set it can be read back later in the same request. We use this to have a value that indicates whether our script was already included or not (think include guards in C, yikes).
Having the same script included in Shoutbox's case would be harmless (it's just a variable declaration) but e.g showing an alert is a use case where you definitely want to prevent the script running more than once!
Happy not flooding the markup with repeated scripts!
Bertrand Le Roy said
I'm not sure you should encourage people to be lazy ;) Script that is not initialization script (and those are instance-specific), should be put in a separate file, always.
Do you have anything about lazy people? :-) I agree with generally putting scripts to external files but this is really handy if your script is like 5 lines but needs 3 values from your model as input: this way it's just simpler to use an inline script.