PageSourceSearch

https://gdekomfort.ru/templates/komfort/resource/js/rscomponent/compare.js

js gdekomfort.ru collected 2026-10-05 02:26:10 UTC 6,238 bytes, 196 lines download raw bytes

1/**
2 * Инициализирует работу функции добавления/удаления товаров к сравнению
3 */
4new class Compare extends RsJsCore.classes.component {
5
6    constructor(settings) {
7        super();
8        let defaults = {
9            comparePage: '.rs-compare-page',
10            compareBlock: '.rs-compare-block',
11            compareButton:'.rs-compare',
12            compareItemsCount: '.rs-compare-items-count',
13            activeCompareClass: 'rs-in-compare',
14            activeClass: 'active',
15            doCompare:'.rs-do-compare',
16            removeItem:'.rs-remove',
17            removeAll: '.rs-remove-all',
18            context:'[data-id]',
19            doCompareWindowTarget: '_blank',
20            doCompareWindowParams: '' //'top=170, left=100, scrollbars=yes, menubar=yes, resizable=yes'
21
22        };
23        this.settings = {...defaults, ...this.getExtendsSettings(), ...settings};
24    }
25
26    /**
27     * Инициализирует подписку на события
28     */
29    init() {
30        this.blocks = document.querySelectorAll(this.settings.compareBlock);
31
32        this.urls = JSON.parse(document.querySelector('[data-compare-url]').dataset.compareUrl);
33
34        this.utils.on('click', this.settings.compareButton, event => this.toggleCompare(event))
35        this.utils.on('click', this.settings.doCompare, event => this.compare(event));
36
37        this.comparePage = document.querySelector(this.settings.comparePage);
38        if (this.comparePage) {
39            this.utils.on('click', this.settings.removeItem, event => this.removeItem(event), this.comparePage);
40            this.utils.on('click', this.settings.removeAll, event => this.removeAll(event), this.comparePage);
41        }
42
43        this.initFirstState();
44        this.initUpdateTitle();
45    }
46
47    add(productId) {
48        this.toggleIcons(productId, true);
49
50        let data = new FormData();
51        data.append('id', productId);
52
53        this.utils.fetchJSON(this.urls.add, {
54            method:'POST',
55            body: data
56        }).then(response => {
57            this.checkActive(response.total);
58        });
59    }
60
61    remove(productId) {
62        this.toggleIcons(productId, false);
63
64        let data = new FormData();
65        data.append('id', productId);
66
67        this.utils.fetchJSON(this.urls.remove, {
68            method:'POST',
69            body: data
70        }).then((response) => {
71            if (response.success) {
72                this.checkActive(response.total);
73            }
74        });
75    }
76
77    /**
78     * Переключает состояние кнопок в сравнение
79     *
80     * @param productId
81     * @param active
82     */
83    toggleIcons(productId, active) {
84        let items = document.querySelectorAll('[data-id="' + productId + '"] ' + this.settings.compareButton);
85        items.forEach((element) => {
86            if (active) {
87                element.classList.add(this.settings.activeCompareClass);
88            } else {
89                element.classList.remove(this.settings.activeCompareClass);
90            }
91            this.updateTitle(element);
92        });
93
94        return items;
95    }
96
97    toggleCompare(event) {
98        event.preventDefault();
99        
100        let id = event.rsTarget.closest(this.settings.context).dataset.id;
101
102        if (event.rsTarget.classList.contains(this.settings.activeCompareClass)) {
103            this.remove( id );
104        } else {
105            this.add( id );
106        }
107        return false;
108    }
109
110    removeItem(event) {
111        event.preventDefault();
112        let id = event.rsTarget.closest('[data-compare-id]').dataset.compareId;
113        this.remove(id);
114    }
115
116    removeAll(event) {
117
118    }
119
120
121    /**
122     * Открывает окно сравнения товаров
123     *
124     * @param event
125     * @returns {boolean}
126     */
127    compare(event) {
128        if (this.blocks[0].classList.contains(this.settings.activeClass)) {
129            window.open(this.urls.compare, this.settings.doCompareWindowTarget, this.settings.doCompareWindowParams);
130        }
131        return false;
132    }
133
134    /**
135     * Добавляет класс activeClass к блоку, если есть хоть один товар в сравнении
136     *
137     * @param count
138     */
139    checkActive(count, productId, productState) {
140
141        this.blocks.forEach((block) => {
142            let counter = block.querySelector(this.settings.compareItemsCount);
143            counter && (counter.innerHTML = count);
144
145            if (count > 0) {
146                block.classList.add(this.settings.activeClass);
147            } else {
148                block.classList.remove(this.settings.activeClass);
149            }
150        });
151
152        if (productId) {
153            this.toggleIcons(productId, productState)
154        }
155    }
156
157
158    /**
159     * Обновляет всплывающую подсказку у кнопки
160     */
161    updateTitle(element) {
162        let title = element.classList.contains(this.settings.activeCompareClass)
163            ? element.dataset.alreadyTitle : element.dataset.title;
164        if (typeof(title) != 'undefined') {
165            element.title = title;
166        }
167    }
168
169    /**
170     * Инициализируем title у значков "сравнить"
171     */
172    initUpdateTitle() {
173        document.querySelectorAll(this.settings.compareButton + '[data-title]')
174            .forEach((element) => this.updateTitle(element));
175    }
176
177    /**
178     * Обновляет состояние кнопки В избранное, при включенном кэшировании
179     */
180    initFirstState() {
181        if (global.compareProducts) {
182            document.querySelectorAll(this.settings.compareButton).forEach((element) => {
183                let productId = element.closest(this.settings.context).dataset.id;
184                if (productId) {
185                    let isActive = global.compareProducts.indexOf(parseInt(productId)) > -1;
186                    isActive ? element.classList.add(this.settings.activeCompareClass)
187                        : element.classList.remove(this.settings.activeCompareClass);
188                }
189            });
190        }
191    }
192
193    onDocumentReady() {
194        this.init();
195    }
196};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.