Posted about 1 month ago. Visible to the public. Repeats.

Events triggered by jQuery cannot be observed by native event listeners

jQuery has a function $.fn.trigger(). You can use it to dispatch an event on a jQuery object:

Copy
let $element = $('.foo') $element.trigger('change')

A caveat is that such an event will be received by jQuery event listeners, but not by native event listeners:

Copy
let $element = $('.foo') $element.on('change', event => console.log('I will be called')) $element[0].addEventListener('change', event => console.log('I WON'T be called')) $element.trigger('change')

This is currently a WONTFIX for jQuery (see closed issues #2476, #3347).

Note that if you trigger a native event instead, it will be received both by jQuery event listeners ($.fn.on()) and native event listeners (Element#addEventListeners()):

Copy
let $element = $('.foo') $element.on('change', event => console.log('I will be called')) $element[0].addEventListener('change', event => console.log('I will also be called')) let event = new CustomEvent('change') $element[0].dispatchEvent(event)

Impact and workarounds

This is an issue if and only if:

  1. Your app has native event listeners registered using Element#addEventListener()
  2. Your app triggers event listeners using jQuery's trigger()

If possible, change your app so it doesn't use jQuery's trigger() function. Instead trigger native events using Element#dispatchEvent() or Unpoly's up.emit().

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Henning Koch
Last edit:
10 days ago
by Dominik Schöler
Keywords:
select2, up-observe
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more