Is there a "best practice" for placing JavaScript code when you have many partial views and JS code that's specific to them?
开发者_开发知识库I feel like I'm creating a maintenance nightmare by having many partial views and then a bunch of independent JavaScript files for them which need to be synced up when there is a partial view change. It appears, for maintenance purposes, better to me to put the JS code with the partial view. But then I'm violating generally accepted practices that all JS code should be at the bottom of the page and not mixed in, and also I'd end up with multiple references to the same JS file (as I'd include a reference in each ASCX for intellisense purposes).
Does anyone have a better idea?
I don't know if there are many more established "best practises" than the ones you have already stated in your question to which you would like to conform.
Lately i've adopted a Html Helper approach to common js/jQuery blocks that i need for certain complex "controls" that need a lot of ajax and UI js assistance. In my most recent case i had two of these "controls" and each one required 3 script blocks.
I how have this helper arrangement where i can use syntax like this:
<%-- // jQuery for Patron --%>
<% =Html.MattyJq().DivListItemSingleSelector("selectPatronItem", "div#matchingPatrons",
"patronsPrevSelectedID","PatronID") %>
<% =Html.MattyJq().EmptyTextInputHelper("patronSearch", "patronsFilterSendEmpty") %>
<% =Html.MattyJq().TextChangeDynamicUpdaterSelect("patronSearch","div#matchingPatrons",
"/patrons/getpatronsitems",500,"patronsFilterSendEmpty","patron",
"patronsPrevSelectedID","selectPatronItem") %>
I have this "Template" folder in my MVC "/Scripts" folder where i place the script blocks and then mark all the "variables" with an escape sequence such that i can swap/regex in my variables that i had passed into the helpers (above) as params.
This way i can reuse the templates and my views are much lighter/cleaner. You'll notice common params in the helpers there - that's when, for example, i have js function names or var
s that are common to more than one script block. It's a sortof way of "linking" the isolated script blocks together.
Lastly i have a common section for the helpers which enables me to "go over" the resulting js/jQuery with a parser if i choose - in my case i use the .NET YUI Compressor to minify the js in Release builds - i'm sure you could add some logic here to ensure that all the script was at the bottom of the page if you liked.
Use a single JS and unobtrusive javascript to layer on behavior to your html pages.
Throwing js all over the place is such a maintenance nightmare, even with firebug.
Remember, always program as if the person maintaining your code is a violent psychopath. ;)
精彩评论