recently-viewed.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Copyright © Magento, Inc. All rights reserved.
  3. * See COPYING.txt for license details.
  4. */
  5. /**
  6. * @api
  7. */
  8. define([
  9. 'jquery',
  10. 'jquery/ui'
  11. ], function ($) {
  12. 'use strict';
  13. $.widget('mage.recentlyViewedProducts', {
  14. options: {
  15. localStorageKey: 'recently-viewed-products',
  16. productBlock: '#widget_viewed_item',
  17. viewedContainer: 'ol'
  18. },
  19. /**
  20. * Bind events to the appropriate handlers.
  21. * @private
  22. */
  23. _create: function () {
  24. var productHtml = $(this.options.productBlock).html(),
  25. productSku = $(this.options.productBlock).data('sku'),
  26. products = JSON.parse(window.localStorage.getItem(this.options.localStorageKey)),
  27. productsLength, maximum, showed, index;
  28. if (products) {
  29. productsLength = products.sku.length;
  30. maximum = $(this.element).data('count');
  31. showed = 0;
  32. for (index = 0; index <= productsLength; index++) {
  33. if (products.sku[index] == productSku || showed >= maximum) { //eslint-disable-line
  34. products.sku.splice(index, 1);
  35. products.html.splice(index, 1);
  36. } else {
  37. $(this.element).find(this.options.viewedContainer).append(products.html[index]);
  38. $(this.element).show();
  39. showed++;
  40. }
  41. }
  42. $(this.element).find(this.options.productBlock).show();
  43. } else {
  44. products = {};
  45. products.sku = [];
  46. products.html = [];
  47. }
  48. products.sku.unshift(productSku);
  49. products.html.unshift(productHtml);
  50. window.localStorage.setItem(this.options.localStorageKey, JSON.stringify(products));
  51. }
  52. });
  53. return $.mage.recentlyViewedProducts;
  54. });