ajax属性execute,AJAX ExecuteCommand

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值