main.js 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. define([
  6. 'underscore',
  7. 'jquery',
  8. './scripts'
  9. ], function (_, $, processScripts) {
  10. 'use strict';
  11. var dataAttr = 'data-mage-init',
  12. nodeSelector = '[' + dataAttr + ']';
  13. /**
  14. * Initializes components assigned to a specified element via data-* attribute.
  15. *
  16. * @param {HTMLElement} el - Element to initialize components with.
  17. * @param {Object|String} config - Initial components' config.
  18. * @param {String} component - Components' path.
  19. */
  20. function init(el, config, component) {
  21. require([component], function (fn) {
  22. if (typeof fn === 'object') {
  23. fn = fn[component].bind(fn);
  24. }
  25. if (_.isFunction(fn)) {
  26. fn(config, el);
  27. } else if ($(el)[component]) {
  28. $(el)[component](config);
  29. }
  30. }, function (error) {
  31. if ('console' in window && typeof window.console.error === 'function') {
  32. console.error(error);
  33. }
  34. return true;
  35. });
  36. }
  37. /**
  38. * Parses elements 'data-mage-init' attribute as a valid JSON data.
  39. * Note: data-mage-init attribute will be removed.
  40. *
  41. * @param {HTMLElement} el - Element whose attribute should be parsed.
  42. * @returns {Object}
  43. */
  44. function getData(el) {
  45. var data = el.getAttribute(dataAttr);
  46. el.removeAttribute(dataAttr);
  47. return {
  48. el: el,
  49. data: JSON.parse(data)
  50. };
  51. }
  52. return {
  53. /**
  54. * Initializes components assigned to HTML elements via [data-mage-init].
  55. *
  56. * @example Sample 'data-mage-init' declaration.
  57. * data-mage-init='{"path/to/component": {"foo": "bar"}}'
  58. */
  59. apply: function (context) {
  60. var virtuals = processScripts(!context ? document : context),
  61. nodes = document.querySelectorAll(nodeSelector);
  62. _.toArray(nodes)
  63. .map(getData)
  64. .concat(virtuals)
  65. .forEach(function (itemContainer) {
  66. var element = itemContainer.el;
  67. _.each(itemContainer.data, function (obj, key) {
  68. if (obj.mixins) {
  69. require(obj.mixins, function () { //eslint-disable-line max-nested-callbacks
  70. var i, len;
  71. for (i = 0, len = arguments.length; i < len; i++) {
  72. $.extend(
  73. true,
  74. itemContainer.data[key],
  75. arguments[i](itemContainer.data[key], element)
  76. );
  77. }
  78. delete obj.mixins;
  79. init.call(null, element, obj, key);
  80. });
  81. } else {
  82. init.call(null, element, obj, key);
  83. }
  84. }
  85. );
  86. });
  87. },
  88. applyFor: init
  89. };
  90. });