-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
100 lines (82 loc) · 4.29 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
(function (data) {
'use strict';
var CardsApp = {};
CardsApp.init = function() {
CardsApp.editCards();
CardsApp.refreshViewCards();
CardsApp.hoverCards();
if (window.history) {
CardsApp.historyApi.add();
CardsApp.historyApi.detectChanges();
}
};
CardsApp.refreshViewCards = function (arg) {
arg = arg || data; // аргумент используется в основном history api для передачи актуального состояния массива
var cardsHolder = document.getElementById('cards-holder'),
cardsSafer = document.createDocumentFragment(),
card; // для кэша html карточек
cardsHolder.innerHTML = ''; // удаляем старые карточки при обновлении массива
for (var i = 0, l = arg.length; l > i; i++) {
card = document.createElement('li'); // добавляем элемент списка для карточки
card.className += 'card card-' + arg[i].type;
if ( i === l - 1 && l !== 1 ) { // добавление сдвига вправо для последней карточки, если их больше 1
card.className += ' card-first';
}
cardsSafer.appendChild(card); // кэшируем для лучшего рендеринга
}
cardsHolder.appendChild( cardsSafer ); // вставляем кэш с элементами
};
CardsApp.hoverCards = function () {
var cardsHolder = document.getElementById('cards-holder'),
cards = document.querySelector('.cards'),
cardClasses = cards.className; // кэшируем список классов
cardsHolder.onmouseenter = function () { // если наводишь на дочерний элемент блока .cards - .cards-holder,
cards.className += ' cards-disable-hover'; // то родительскому (cards) добавляется класс (cards-disable-hover),
}; // что меняет цвет его бэкграунда
cardsHolder.onmouseleave = function () {
cards.className = cardClasses;
};
};
CardsApp.addCard = function (type) {
type = type || 'narrow'; // если не задан тип карты, ставим по-умолчанию узкую
data.push(
{
type: type
}
);
};
CardsApp.removeCard = function () {
if ( data.length > 0 ) { // чтобы не пыталось удалить из пустого массива
var cardsLength = data.length;
data.splice(cardsLength - 1, 1);
}
};
CardsApp.editCards = function () {
var cards = document.querySelector('.cards');
cards.addEventListener("click", function(e) {
if ( e.shiftKey ) { // ловим нажатые кнопки
if ( e.altKey ) {
CardsApp.addCard('wide');
} else {
CardsApp.addCard('narrow'); // если только шифт
}
} else {
CardsApp.removeCard(); // если только клик
}
CardsApp.refreshViewCards(); // после каждого изменения обновляем вьюху
CardsApp.historyApi.add(); // и добавляем это изменение в хистори апи
});
};
CardsApp.historyApi = {
add: function () {
history.pushState(data, null); // сохраняем в метод state актуальный массив
},
detectChanges: function() {
window.addEventListener('popstate', function(e) { // ловим нажатия стрелок истории, передаем в аргумент данные перехода
data = e.state; // обновляем массив данными из истории
CardsApp.refreshViewCards(data); // используем его во вью
});
}
};
CardsApp.init();
}(cards));