Posted over 8 years ago. Visible to the public.

Unobtrusive JavaScript and AJAX

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

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

any more, but instead you write

Copy
$.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

Copy
$(newContent).activateUnobtrusiveJavascript();

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

Code for the helper

Copy this into your project:

Copy
// 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(); });
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Avatar
Tobias Kraze
Last edit:
5 months ago
by Henning Koch
Keywords:
jQuery
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more