Version 1
[yaffs-website] / web / core / modules / system / js / system.js
1 /**
2  * @file
3  * System behaviors.
4  */
5
6 (function ($, Drupal, drupalSettings) {
7
8   'use strict';
9
10   // Cache IDs in an array for ease of use.
11   var ids = [];
12
13   /**
14    * Attaches field copy behavior from input fields to other input fields.
15    *
16    * When a field is filled out, apply its value to other fields that will
17    * likely use the same value. In the installer this is used to populate the
18    * administrator email address with the same value as the site email address.
19    *
20    * @type {Drupal~behavior}
21    *
22    * @prop {Drupal~behaviorAttach} attach
23    *   Attaches the field copy behavior to an input field.
24    */
25   Drupal.behaviors.copyFieldValue = {
26     attach: function (context) {
27       // List of fields IDs on which to bind the event listener.
28       // Create an array of IDs to use with jQuery.
29       for (var sourceId in drupalSettings.copyFieldValue) {
30         if (drupalSettings.copyFieldValue.hasOwnProperty(sourceId)) {
31           ids.push(sourceId);
32         }
33       }
34       if (ids.length) {
35         // Listen to value:copy events on all dependent fields.
36         // We have to use body and not document because of the way jQuery events
37         // bubble up the DOM tree.
38         $('body').once('copy-field-values').on('value:copy', this.valueTargetCopyHandler);
39         // Listen on all source elements.
40         $('#' + ids.join(', #')).once('copy-field-values').on('blur', this.valueSourceBlurHandler);
41       }
42     },
43     detach: function (context, settings, trigger) {
44       if (trigger === 'unload' && ids.length) {
45         $('body').removeOnce('copy-field-values').off('value:copy');
46         $('#' + ids.join(', #')).removeOnce('copy-field-values').off('blur');
47       }
48     },
49
50     /**
51      * Event handler that fill the target element with the specified value.
52      *
53      * @param {jQuery.Event} e
54      *   Event object.
55      * @param {string} value
56      *   Custom value from jQuery trigger.
57      */
58     valueTargetCopyHandler: function (e, value) {
59       var $target = $(e.target);
60       if ($target.val() === '') {
61         $target.val(value);
62       }
63     },
64
65     /**
66      * Handler for a Blur event on a source field.
67      *
68      * This event handler will trigger a 'value:copy' event on all dependent
69      * fields.
70      *
71      * @param {jQuery.Event} e
72      *   The event triggered.
73      */
74     valueSourceBlurHandler: function (e) {
75       var value = $(e.target).val();
76       var targetIds = drupalSettings.copyFieldValue[e.target.id];
77       $('#' + targetIds.join(', #')).trigger('value:copy', value);
78     }
79   };
80
81 })(jQuery, Drupal, drupalSettings);