Drupal investigation

system.js 2.5KB

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