Create an Ajax Command RebindLinkCommand

Created on 21 January 2025, about 14 hours ago

Problem/Motivation

If an ajax link needs to be updated in ajax, we need to execute this kind of js code (as stated here ) to rebind ajax links :

$('#my-link')
  // Change the link href.
  .attr('href', '/my-new-url')
  // Unbind the old Ajax click handler.
  .unbind('click');
// Remove the once() so it will get processed again.
once.remove('ajax', '#my-link');
// Attach the Ajax action to this link.
Drupal.ajax.bindAjaxLinks(document.body);

The attr and unbind can be triggered with the InvokeCommand so we only need a command to rebindLinks (but maybe have a command that execute the entire js code above is better).

Proposed resolution

Create an Ajax Command RebindLinkCommand that will execute a javascript code. Something like this :

declare(strict_types=1);

namespace Drupal\Core\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class RebindLinksCommand implements CommandInterface {

  public function __construct(protected string $selector) {}

  public function render(): array {
    return [
      'command' => 'rebindAjaxLinks',
      'selector' => $this->selector,
    ];
  }

}

and a .js file like this :

(function ($, Drupal, once) {
  'use strict';

  // @see https://www.drupal.org/docs/develop/drupal-apis/ajax-api/ajax-dialog-boxes
  Drupal.AjaxCommands.prototype.rebindAjaxLinks = function (ajax, response, status) {
    once.remove('ajax', response.selector);
    Drupal.ajax.bindAjaxLinks(document.body);
  };

})(jQuery, Drupal, once);

Feature request
Status

Active

Version

11.1 🔥

Component

ajax system

Created by

🇫🇷France pbonnefoi

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

Comments & Activities

Production build 0.71.5 2024