Unobtrusive JavaScript and AJAX

Updated . Posted . Visible to the public. Deprecated.

We no longer use jQuery.

Some replacements for $.unobtrusive() are:

Attached (see below) is some code to allow using unobtrusive JavaScript on pages fetched with an AJAX call.

After you included it, you now do not use the usual

$(function() { 
  $('.some_tag').activateStuff(); 
});

any more, but instead you write

$.unobtrusive(function() {
  $(this).find('.some_tag').activateStuff();
});

that is

  • $.unobtrusive() instead of $()
  • don't do stuff to the whole page, but just to elements nested below $(this)

Normal pages work as before (your $.unobtrusive functions are called automatically), but you gain the option to manually run those by calling

$(newContent).activateUnobtrusiveJavascript(); 

You would always run this on any DOM-nodes you have just inserted.

Code for the helper

Copy this into your project:

// Define $.unobtrusive() to register new element activation callbacks
$.unobtrusive = function(callback) {
  $(document).on('activate-unobtrusive-javascript', function(event, root) {
    $(root).each(callback);
  });
}

// Define a function for all jQuery collections to manually run activation callbacks on that element
$.fn.activateUnobtrusiveJavascript = function() {
  this.each(function() {
    $(document).trigger('activate-unobtrusive-javascript', this);
  });
}

// Activate the entire DOM on initial page load
$(function() {
  $(document).activateUnobtrusiveJavascript();
});
Tobias Kraze
Last edit
Henning Koch
Keywords
jQuery
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2010-08-24 17:21)