2018-11-23 12:29:20 +00:00
/ * *
* @ file
* JavaScript behaviors for computed elements .
* /
( function ( $ , Drupal , debounce ) {
'use strict' ;
Drupal . webform = Drupal . webform || { } ;
Drupal . webform . computed = Drupal . webform . computed || { } ;
Drupal . webform . computed . delay = Drupal . webform . computed . delay || 500 ;
/ * *
* Initialize computed elements .
*
* @ type { Drupal ~ behavior }
* /
Drupal . behaviors . webformComputed = {
attach : function ( context ) {
$ ( context ) . find ( '.js-webform-computed' ) . once ( 'webform-computed' ) . each ( function ( ) {
// Get computed element and parent form.
var $element = $ ( this ) ;
var $form = $element . closest ( 'form' ) ;
// Get elements that are used by the computed element.
var elementKeys = $ ( this ) . data ( 'webform-element-keys' ) . split ( ',' ) ;
if ( ! elementKeys ) {
return ;
}
2019-01-24 08:00:03 +00:00
// Get computed element triggers.
var inputs = [ ] ;
2018-11-23 12:29:20 +00:00
$ . each ( elementKeys , function ( i , key ) {
2019-01-24 08:00:03 +00:00
// Exact input match.
inputs . push ( ':input[name="' + key + '"]' ) ;
// Sub inputs. (aka #tree)
inputs . push ( ':input[name^="' + key + '["]' ) ;
2018-11-23 12:29:20 +00:00
} ) ;
2019-01-24 08:00:03 +00:00
var $triggers = $form . find ( inputs . join ( ',' ) ) ;
// Add event handler to computed element triggers.
$triggers . on ( 'keyup change' ,
debounce ( triggerUpdate , Drupal . webform . computed . delay ) ) ;
2018-11-23 12:29:20 +00:00
// Initialize computed element update which refreshes the displayed
// value and accounts for any changes to the #default_value for a
// computed element.
2019-01-24 08:00:03 +00:00
triggerUpdate ( true ) ;
2018-11-23 12:29:20 +00:00
2019-01-24 08:00:03 +00:00
function triggerUpdate ( initialize ) {
2018-11-23 12:29:20 +00:00
// Prevent duplicate computations.
// @see Drupal.behaviors.formSingleSubmit
2019-01-24 08:00:03 +00:00
if ( initialize !== true ) {
var formValues = $triggers . serialize ( ) ;
var previousValues = $element . attr ( 'data-webform-computed-last' ) ;
if ( previousValues === formValues ) {
return ;
}
$element . attr ( 'data-webform-computed-last' , formValues ) ;
2018-11-23 12:29:20 +00:00
}
// Add loading class to computed wrapper.
$element . find ( '.js-webform-computed-wrapper' )
. addClass ( 'webform-computed-loading' ) ;
// Trigger computation.
$element . find ( '.js-form-submit' ) . mousedown ( ) ;
}
} ) ;
}
} ;
} ) ( jQuery , Drupal , Drupal . debounce ) ;