mage.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. (function (root, factory) {
  6. 'use strict';
  7. if (typeof define === 'function' && define.amd) {
  8. define([
  9. 'jquery',
  10. 'mage/apply/main'
  11. ], factory);
  12. } else {
  13. factory(root.jQuery);
  14. }
  15. }(this, function ($, mage) {
  16. 'use strict';
  17. /**
  18. * Main namespace for Magento extensions
  19. * @type {Object}
  20. */
  21. $.mage = $.mage || {};
  22. /**
  23. * Plugin mage, initialize components on elements
  24. * @param {String} name - Components' path.
  25. * @param {Object} config - Components' config.
  26. * @returns {JQuery} Chainable.
  27. */
  28. $.fn.mage = function (name, config) {
  29. config = config || {};
  30. this.each(function (index, el) {
  31. mage.applyFor(el, config, name);
  32. });
  33. return this;
  34. };
  35. $.extend($.mage, {
  36. /**
  37. * Handle all components declared via data attribute
  38. * @return {Object} $.mage
  39. */
  40. init: function () {
  41. mage.apply();
  42. return this;
  43. },
  44. /**
  45. * Method handling redirects and page refresh
  46. * @param {String} url - redirect URL
  47. * @param {(undefined|String)} type - 'assign', 'reload', 'replace'
  48. * @param {(undefined|Number)} timeout - timeout in milliseconds before processing the redirect or reload
  49. * @param {(undefined|Boolean)} forced - true|false used for 'reload' only
  50. */
  51. redirect: function (url, type, timeout, forced) {
  52. var _redirect;
  53. forced = !!forced;
  54. timeout = timeout || 0;
  55. type = type || 'assign';
  56. /**
  57. * @private
  58. */
  59. _redirect = function () {
  60. window.location[type](type === 'reload' ? forced : url);
  61. };
  62. timeout ? setTimeout(_redirect, timeout) : _redirect();
  63. },
  64. /**
  65. * Checks if provided string is a valid selector.
  66. * @param {String} selector - Selector to check.
  67. * @returns {Boolean}
  68. */
  69. isValidSelector: function (selector) {
  70. try {
  71. document.querySelector(selector);
  72. return true;
  73. } catch (e) {
  74. return false;
  75. }
  76. }
  77. });
  78. /**
  79. * Init components inside of dynamically updated elements
  80. */
  81. $('body').on('contentUpdated', function () {
  82. if (mage) {
  83. mage.apply();
  84. }
  85. });
  86. return $.mage;
  87. }));