Behavior context is a string, not a DOM object

Created on 6 September 2021, almost 3 years ago
Updated 22 March 2024, 3 months ago

Problem/Motivation

When used in conjunction with the BLazy module an error is triggered when cbox_complete fires. The specific error:
Cannot use 'in' operator to search for 'length' in #cboxLoadedContent

I had thought it was an issue in BLazy but in digging I believe it may be an issue here. the function definition for attachBehaviors (drupal.js:106) docblock defines context as follows:

 * @param context
 *   An element to attach behaviors to. If none is given, the document element
 *   is used.

I read that as requiring a dom element, not a selector, though I can't find any documentation either way. Sending $('#cboxLoadedContent') as the argument to attachBehaviors fixes the problem in this case. This likely hasn't cropped up since the usual use of context is as a, well, context in a selector. That wouldn't be affected by a DOM versus selector change, whereas any context assuming that the context is a DOM element and attempting to access it as an array would go sideways.

If the assumption is that context can be either a selector or object then please close this out and I will open a ticket with BLazy to sanitize the variables, if assuming an object is fair than the bug belongs here.

Steps to reproduce

Attempt to refer to context as an array in a behavior. The specific example triggering the error is as follows, but any attempt should have the same result.

  Drupal.behaviors.blazy = {
    attach: function (context) {
      // Drupal.attachBehaviors already does this so if this is necessary,
      // someone does an invalid call. But let's be robust here.
      context = context || document;

      // Fixes for jQuery integration with AJAX where context might be an array.
      if ('length' in context) {
        context = context[0];
      }

specifically the if ('length' in context) { line.

Proposed resolution

change `Drupal.attachBehaviors('#cboxLoadedContent');` to `Drupal.attachBehaviors($('#cboxLoadedContent'));`

πŸ› Bug report
Status

Fixed

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States wolffereast

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

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024