I’m using EditorTemplates for things like DateTime, Colors, etc. My forms, which may contain quite a bit of these templates, are primarily loaded via Ajax as a partial view.
Rather than have a bunch of jQuery initialization scripts at the bottom of each editor template, is there a conceptual way to do it only once per response? Lets say the you have 10 date time pickers, on one form, it would be really silly to pass down the same initialization code 10 times.
Placing the initialization script on the main form with the 10 date pickers would be efficient (certainly doesn’t do much to keep code isolated to the datetime editor template), but then there’s other cases where you may just want to have one date time picker on a different form or two or three, and now you’re duplicating those scripts across multiple views in your code.
So how can I still leverage editor templates the right way here? I think I’m looking for something like —
EnsureThisScriptIsOutputOncePerThisResponse(<script>$('.datepicker').datepicker("insert lengthy config here");</script>)
to add to the bottom of the editor template that works with partial views rendered via AJAX.
One thing we did on our project was to have a startup.js file that extends the unobtrusive javascript pattern by utilizing data attributes for configuring things like that. An example for ours is buttons. Let’s say I had the following html:
the startup file looks for buttons something like this:
This makes common jQuery UI initialization code much easier to manage, and we created HtmlHelper extensions to easily fill in the data attributes for the stuff we need/use.