Motivation
I'm not sure this has been proposed or implemented yet. Can't find it in the AJAX API right now.
Sometimes I need to run in a server-side AJAX callback some actions that are not necessary linked to a DOM element, but being a namespaced function.
I added in my projects an ExecuteCommand to deal with this situation
Proposed resolution
Server-side code
namespace Drupal\Core\Ajax\;
use Drupal\Core\Ajax\CommandInterface;
class ExecuteCommand implements CommandInterface
{
private $function;
private $args;
public function __construct ( $function, array $args = [] )
{
$this->function = $function;
$this->args = $args;
}
public function render ()
{
return [ 'command' => 'ExecuteCommand'
, 'function' => $this->function
, 'args' => $this->args
, ];
}
}
Browser side jquery
( function ( $, Drupal ) {
Drupal.AjaxCommands.prototype.ExecuteCommand = function ( ajax, response ) {
var namespaces = response.function.split ( '.' );
var func = namespaces.pop ();
var context = window;
var args = [];
// Build namespace path
for ( var i = 0; i < namespaces.length; i++ )
{
context = context[namespaces[i]];
}
// Explode arguments
if ( typeof response.args === 'object' )
{
args = Object.values ( response.args );
}
else if ( Array.isArray(response.args) == true )
{
args = response.args;
}
// Call function
if ( context !== undefined )
{
return context[func].apply ( context, args );
}
// Failed to execute command
return false;
};
} ) ( jQuery, Drupal );
User interface changes
None
API changes
Add above code
Data model changes
None
Release notes snippet