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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)