2 * @file entity_browser.command_queue.js
5 (function ($, Drupal) {
10 * Namespace for command queue functionality.
12 * Command queue provides functionality to queue ajax commands in front-end
13 * and execute them in one ajax request in backend. All commands triggered
14 * during ajax request execution, will be queue and executed after response
15 * from previous ajax request is received.
19 Drupal.entityBrowserCommandQueue = {};
22 * Queue container for keeping commands for next queue execution. (protected)
26 var commandsQueue = {};
29 * Registers behaviours related to Ajax commands execution.
31 Drupal.behaviors.entityBrowserCommandQueue = {
32 attach: function (context) {
33 var handler = $(context).find('[name="ajax_commands_handler"]');
35 handler.once('register-execute-commands')
36 .bind('execute-commands', Drupal.entityBrowserCommandQueue.executeCommands);
41 * Action to queue command for future execution.
43 * @param {string} commandName
44 * Command name, that will be executed.
45 * @param {Array} commandParam
46 * Params for command. If command already exists in queue params will be
47 * added to end of list.
49 Drupal.entityBrowserCommandQueue.queueCommand = function (commandName, commandParam) {
50 if (!commandsQueue[commandName]) {
51 commandsQueue[commandName] = [];
54 commandsQueue[commandName].push(commandParam);
58 * Handler for executing queued commands over Ajax.
60 * @param {object} event
62 * @param {boolean} addedCommand
63 * Execution of queued commands is triggered after new command is added.
65 Drupal.entityBrowserCommandQueue.executeCommands = function (event, addedCommand) {
66 var handler = $(this);
67 var handlerElement = handler[0];
68 var runningAjax = Drupal.entityBrowserCommandQueue.isAjaxRunning(handlerElement, 'execute_js_commands');
69 var filledQueue = !$.isEmptyObject(commandsQueue);
71 if (!runningAjax && filledQueue) {
72 handler.val(JSON.stringify(commandsQueue));
74 // Clear Queue after command is set to handler element.
77 // Trigger event to execute event with defined command.
78 handler.trigger('execute_js_commands');
80 else if (!addedCommand && filledQueue) {
81 setTimeout($.proxy(Drupal.entityBrowserCommandQueue.executeCommands, handlerElement), 200);
86 * Search is there current Ajax request executing for current event.
88 * @param {element} handlerElement
89 * Element on what event is triggered.
90 * @param {string} eventName
94 * Returns true if ajax event is still running for element.
96 Drupal.entityBrowserCommandQueue.isAjaxRunning = function (handlerElement, eventName) {
97 var ajax_list = Drupal.ajax.instances;
99 for (var i = 0; i < ajax_list.length; i++) {
100 if (ajax_list[i] && ajax_list[i].event === eventName && ajax_list[i].element === handlerElement && ajax_list[i].ajaxing) {