Read more

Listening to bubbling events in Prototype is easy

Arne Hartherz
April 09, 2014Software engineer at makandra GmbH

If you come across an (older) application that is using Prototype Show archive.org snapshot instead of jQuery, you may often see events bound to single elements only, like this:

$('foo').observe('change', updateThings);
$('bar').observe('change', updateThings);
$('baz').observe('change', updateThings);
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

If you are calling only one method in each case, this is unnecessarily ugly. Also, when your page contents have been replaced via AJAX (like sections of a form after choosing something), those event hooks will no longer work.

Instead, just do it similar to what you know from jQuery:

document.on('change', '#foo, #bar, #baz', updateThings);

Or, just apply a nice data attribute to the form fields, and look for that in your JavaScript code:

document.on('change', '[data-requires-update]', updateThings);

If you are interested in the element that was triggered the event, simply take an event argument and look at event.target.

Posted by Arne Hartherz to makandra dev (2014-04-09 18:05)