Is ther开发者_C百科e a tutorial or explanation how MVC3 implements unobstrusive javascript using HTML5 data tags? I would like to know how I can extend this practice for my own javascript, espescially, how are the data tags efficiently parsed to execute javascript, to attach event handlers, etc.?
In ASP.NET MVC 1 and 2, client side validation and any AJAX behavior meant that ASP.NET MVC would automatically generate javascript for validation or AJAX class. The result was a <script>
tag with javascript embedded that would be outputted on the HTML page or data in the event handlers of an input (like onclick
).
Unobtrusive javascript eliminates the need to embedded javascript in the HTML page by placing all necessary things in data-
attributes on the element. With this in place, jquery.validate.unobtrusive
will validate and do AJAX class based on the information in the data-
attributes of the input control.
For more details, take a look at this asp.net mvc 3 tutorial which offers a quick example. The unobtrusive explanation is towards the end under the second Enabling Client-Side Validation
.
Take a look at this blog post which displays the difference of output for unobtrusive and normal validation.
Basically it's just using jQuery to attach event handlers rather than putting script directly in the html attributes.
For example a document ready event containing
$("#button1").click(DoStuff);
and the html
<button id="button1" />
is equivalent to
<button id="button1" onclick="DoStuff()" />
In this example it's not a huge difference, but for more complex cases it makes the code much cleaner, especially if you want to use anonymous callback functions.
Look in the unobtrusive script files (like jquery.unobtrusive-ajax.js) where you'll find it's just a case of using selectors to find elements with data- attributes.
For example:
$("a[data-ajax=true]").live("click", function (evt) {
evt.preventDefault();
...
});
$("form[data-ajax=true]").live("submit", function (evt) {
...
});
I've started using my own data- attributes to hookup features like autocomplete and datepicker. For example, adding an input with a data-autocomplete attribute pointing to a remote data source, then using jQuery to wire it up unobtrusively.
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
Demonstrated here, if you are interested: http://www.pluralsight-training.net/microsoft/players/PSODPlayer.aspx?author=scott-allen&name=mvc3-building-ajax&mode=live&clip=0&course=aspdotnet-mvc3-intro
精彩评论