Introduction to Unobtrusive Javascript

Unobtrusive JavaScript is an approach to the use of JavaScript in web pages to achieve its basic principles as below: • Separation of functionality (the “behavior layer”) from a Web page’s structure/content and presentation. • Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability) • Progressive enhancement to support user agents that may not support advanced JavaScript functionality.
Separation of behavior from markup
Traditionally Javascript is fed into inline HTML document markup as a functions or query. Lets consider typical implementation of JS form validation when placed inline:
<input type="text" name="date" onchange="validateDate()" />
Adherents of “Unobtrusive JavaScript” contend that purpose of markup is to describe a documents structure, not its programmatic behavior .Also the inline event handlers are harder to use and maintain, when one needs to set handlers for several events on a single element. The unobtrusive solution is to register necessary event handlers programmatically rather than inline. If we consider same example above it can be achieved as below:

<input type="text" name="date" id="date" />
A script that runs when the page is first loaded into the browser can then look for the relevant element(s) and set them up accordingly:window.onload = function() { document.getElementById('date').onchange = validateDate; };

What To Do: AjaxOptions

The AjaxHelper extension methods – ActionLink and RouteLink for Ajax links, and BeginForm and BeginRouteForm for Ajax forms – have APIs which are very similar to their HtmlHelper counterparts.The properties here are all used to tell MVC exactly what you want your Ajax call to do.The primary difference is that the AjaxHelper versions all take an additional parameter in the form of the AjaxOptions class:
public class AjaxOptions {
public string Confirm { get; set; }
public string HttpMethod { get; set; }
public InsertionMode InsertionMode { get; set; }
public int LoadingElementDuration { get; set; }
public string LoadingElementId { get; set; }
public string OnBegin { get; set; }
public string OnComplete { get; set; }
public string OnFailure { get; set; }
public string OnSuccess { get; set; }
public string UpdateTargetId { get; set; }
public string Url { get; set; }
}

Rendering: Traditional

When unobtrusive mode is off, MVC will render inline JavaScript on your <a> and <form> elements that’s dependent on the ASP.NET Ajax library (MicrosoftAjax.js) and the MVC Ajax library that uses ASP.NET Ajax (MicrosoftMvcAjax.js):
<form
action="/ajax/callback"
id="form0"
method="post"
onclick="Sys.Mvc.AsyncForm.handleClick(this, new Sys.UI.DomEvent(event));"
onsubmit="Sys.Mvc.AsyncForm.handleSubmit(this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, loadingElementId: 'loading', updateTargetId: 'updateme' });">
This behavior is identical to the behavior in MVC 1.0 and MVC 2.

Rendering: Unobtrusive

When unobtrusive Ajax mode is enabled in MVC, the HTML that we generate looks significantly different:
<form
action="/ajax/callback"
data-ajax="true"
data-ajax-loading="#loading"
data-ajax-mode="replace"
data-ajax-update="#updateme"
method="post">
Probably the first thing you’ll notice is that the HTML is very readable (and thus, very tweak-able when doing debugging). Using simple names and values increases readability. Another thing that’s obvious is that the rendered size of the HTML content is quite a bit smaller in unobtrusive mode, even with semi-verbose attribute names. The HTML is HTML 5-compatible, using the extensible attribute (data-) syntax. We’re also using CSS selectors for increased flexibility on the client-side for things choosing the loading and update elements.

Enabling Unobtrusive Ajax

In MVC 3, we have a single flag to turn on unobtrusive JavaScript mode, which enables both unobtrusive Ajax and unobtrusive client validation . Unobtrusive JavaScript mode is turned off by default . However, we have it turned on in the MVC 3 project template, so new projects will begin using the unobtrusive JavaScript support by default. To turn unobtrusive JavaScript mode on/off by default for the entire application, you can use Web.config:
<configuration>
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
You can also turn it on or off with code:
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
Using code to turn it on or off actually behaves contextually. If that line of code is present in your Global.asax file, then it turns unobtrusive JavaScript on or off for the whole application. If it appears within your controller or view, on the other hand, it will turn it on or off for the current action only.
In addition to setting the flag, you will also need to include two script files: jQuery (~/Scripts/jquery-1.4.1.js) and the MVC plugin for unobtrusive Ajax with jQuery (~/Scripts/jquery.unobtrusive-ajax.js).
An interesting note: since there is no actual JavaScript being emitted when you use unobtrusive Ajax, if you forget to include one or the other script, you won’t see any errors when attempting to submit the Ajax request; it will simply behave like a non-Ajax request.

Comments

Popular posts from this blog

The Top 15 Google Products for People Who Build Websites

Google Translator using Windows forms

5 Useful Tricks for Ubuntu Power Users