Read more

Unobtrusive JavaScript and AJAX

Tobias Kraze
August 24, 2010Software engineer at makandra GmbH

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.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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();
});
Posted by Tobias Kraze to makandra dev (2010-08-24 19:21)