Race condition for simultaneously attached behavior

Created on 27 November 2024, 7 days ago

Problem/Motivation

If Drupal.attachBehaviors() is called simultaneously, the module fails to process them correctly because of a race condition.

It is happening because the currently active element is stored in the global setting, settings.quicklink.quicklinkConfig.el, which is instantly overridden for any consecutive attached behavior. This leads to an issue that only the latter element will be processed.

Real case scenario: I have an improved Drupal pager with a regular page link and a "Load more" button. When a user clicks on the "Load more", it loads items from the next page and adds them to the list. It also updates the pager element to reflect changes in the link list. So, there are two behaviors associated with it: one for updating the list of items and one for the pager. First, it triggers the behavior for the pager, then it triggers the behaviors for the items, but because of the race condition, it only processes the list of items. This makes it impossible to preload the links for the pager anymore.

Steps to reproduce

Drupal.attachBehaviors(document.querySelector('.page-header')); Drupal.attachBehaviors(document.querySelector('.page-footer')

The only element which will be processed is .page-footer

Take a look at el. The output is given by console.log(settings.quicklink.quicklinkConfig); right before quicklink.listen(settings.quicklink.quicklinkConfig);.

Proposed resolution

The element reference should be added dynamically for each behavior's attachments and not rely on a global element storage.

🐛 Bug report
Status

Active

Version

2.0

Component

Code

Created by

🇷🇺Russia niklan Russia, Perm

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024