Skip to content

Instantly share code, notes, and snippets.

@dmitru
Created April 9, 2017 16:20
Show Gist options
  • Save dmitru/5cea49f3665c14f17de6cf1acf72988b to your computer and use it in GitHub Desktop.
Save dmitru/5cea49f3665c14f17de6cf1acf72988b to your computer and use it in GitHub Desktop.
'use strict';
function setupMap() {
var titles = [
'Большая уютная квартира',
'Маленькая неуютная квартира',
'Огромный прекрасный дворец',
'Маленький ужасный дворец',
'Красивый гостевой домик',
'Некрасивый негостеприимный домик',
'Уютное бунгало далеко от моря',
'Неуютное бунгало по колено в воде'
];
var types = ['flat', 'house', 'bungalo'];
var checks = ['12:00', '13:00', '14:00'];
var features = [
'wifi',
'dishwasher',
'parking',
'washer',
'elevator',
'conditioner'
];
var photos = [];
function getRandomNumber(min, max) {
return Math.round(Math.random() * (max - min)) + min;
}
function getRandomValue(array) {
var value = array[Math.floor(Math.random() * array.length)];
return value;
}
function createPlaces(count) {
var arrayPlace = [];
for (var i = 0; i < count; i++) {
var place = {};
var locationX = getRandomNumber(300, 900);
var locationY = getRandomNumber(100, 500);
place.author = {
avatar: 'img/avatars/user' + '0' + getRandomNumber(1, 8) + '.png'
};
place.offer = {
title: getRandomValue(titles),
address: locationX + ', ' + locationY,
price: getRandomNumber(1000, 1000000),
type: getRandomValue(types),
rooms: getRandomNumber(1, 5),
guests: getRandomNumber(1, 12),
checkin: getRandomValue(checks),
checkout: getRandomValue(checks),
features: getRandomValue(features),
description: ' ',
photos: getRandomValue(photos)
};
place.location = {
x: locationX,
y: locationY
};
arrayPlace.push(place);
}
return arrayPlace;
}
function generateLabels(place) {
// place - это массив. давай переназовем его как places, или arrayPlaces
place.forEach(function (newdiv) {
// newdiv - это элемент массива arrayPlaces, и это вовсе не div.
// давай переназовем получше, например place
// т.е. будет так: arrayPlaces.forEach(function (place) {
var pinElement = createPinElement(newdiv);
var parent = document.querySelector('.tokyo__pin-map');
parent.appendChild(pinElement);
pinElement.addEventListener('click', function (evt) {
// вот эти 4 строчки: от сюда...
var fragment = document.createDocumentFragment();
fragment.appendChild(clonePlace(newdiv));
var offerDialog = document.querySelector('.dialog__panel');
offerDialog.replaceWith(fragment);
// ...до сюда
// повторяются внутри createPinElement в листенере.
// оба раза это происходит прямо перед вызовом onPinClick...
// Повторяющийся код - это плохо!
// перемеси этот код в onPinClick, чтобы не повторяться.
onPinClick(pinElement);
});
});
}
// отдели пустой строкой
function createPinElement(data) {
var newDiv = document.createElement('div');
newDiv.className = 'pin';
newDiv.style.left = data.location.x + 'px';
newDiv.style.top = data.location.y + 'px';
var avatarImg = document.createElement('img');
avatarImg.className = 'rounded';
avatarImg.style.marginLeft = 6 + 'px';
avatarImg.style.marginTop = 6 + 'px';
avatarImg.style.width = 44 + 'px';
avatarImg.style.height = 46 + 'px';
avatarImg.setAttribute('tabindex', '0');
avatarImg.src = data.author.avatar;
// отдели пустой строкой
avatarImg.addEventListener('keypress', function (evt) {
if (evt.keyCode === 13) {
var fragment = document.createDocumentFragment();
fragment.appendChild(clonePlace(data));
var offerDialog = document.querySelector('.dialog__panel');
offerDialog.replaceWith(fragment);
onPinClick(newDiv);
}
});
// отдели пустой строкой
newDiv.appendChild(avatarImg);
return newDiv;
}
var lodgeTemplate = document.querySelector('#lodge-template');
function clonePlace(places) {
var lodgeType;
if (places.offer.type === 'bungalo') {
lodgeType = 'Бунгало';
} else if (places.offer.type === 'flat') {
lodgeType = 'Квартира';
} else if (places.offer.type === 'house') {
lodgeType = 'Дом';
}
// отдели строкой
var dialogTitle = document.querySelector('.dialog__title');
var oldImg = dialogTitle.querySelector('img');
var newImg = document.createElement('img');
newImg.src = places.author.avatar;
dialogTitle.replaceChild(newImg, oldImg);
var featuresElement = document.createElement('span');
featuresElement.className = 'feature__image feature__image--' + places.offer.features;
var placeElement = lodgeTemplate.content.cloneNode(true);
placeElement.querySelector('.lodge__title').textContent = places.offer.title;
placeElement.querySelector('.lodge__address').textContent = places.offer.address;
placeElement.querySelector('.lodge__price').textContent = places.offer.price + '₽' + '/ночь';
placeElement.querySelector('.lodge__type').textContent = lodgeType;
placeElement.querySelector('.lodge__rooms-and-guests').textContent = 'Для ' + places.offer.guests + ' гостей в ' + places.offer.rooms + ' комнатах';
placeElement.querySelector('.lodge__checkin-time').textContent = 'Зезд после ' + places.offer.checkin + ', выезд до ' + places.offer.checkout;
placeElement.querySelector('.lodge__features').appendChild(featuresElement);
placeElement.querySelector('.lodge__description').textContent = places.offer.description;
return placeElement;
}
// давай перепишем как:
// generateLabels(createPlaces(8));
// т.е. без промежуточной переменной.
// так меньше вероятности, что ты ее случайно где-нибудь
// внутри другой функции по ошибке используешь.
var places = createPlaces(8);
generateLabels(places);
function onPinClick(pinElement) {
clearPin();
var dialog = document.querySelector('.dialog');
var dialogPanel = dialog.querySelector('.dialog__panel');
var dialogTitle = dialog.querySelector('.dialog__title');
if (!pinElement.classList.contains('pin--active')) {
pinElement.classList.add('pin--active');
dialogTitle.style.display = 'block';
} else {
pinElement.classList.remove('pin--active');
dialogTitle.style.display = 'none';
dialogPanel.style.display = 'none';
}
}
function clearPin() {
var pin = document.querySelector('.pin--active');
if (pin !== null) {
pin.classList.remove('pin--active');
}
}
function closePopup() {
var pin = document.querySelector('.pin--active');
var dialog = document.querySelector('.dialog');
var dialogPanel = dialog.querySelector('.dialog__panel');
var dialogTitle = dialog.querySelector('.dialog__title');
// отдели пустой строкой
if (pin === null) {
dialogTitle.style.display = 'none';
dialogPanel.style.display = 'none';
} else if (pin.classList.contains('pin--active')) {
pin.classList.remove('pin--active');
dialogTitle.style.display = 'none';
dialogPanel.style.display = 'none';
}
}
var dialogClose = document.querySelector('.dialog__close');
var escKeyCode = 27;
// заведи такую же константу для enter, и используй в своем коде
dialogClose.addEventListener('click', function (evt) {
closePopup();
});
document.addEventListener('keydown', function (evt) {
if (evt.keyCode === escKeyCode) {
closePopup();
}
});
var timeIn = document.querySelector('#time');
var timeOut = document.querySelector('#timeout');
timeIn.onchange = function () {
timeOut.selectedIndex = this.selectedIndex;
};
timeOut.onchange = function () {
timeIn.selectedIndex = this.selectedIndex;
};
var typeRealty = document.querySelector('#type');
var priceRealty = document.querySelector('#price');
typeRealty.onchange = function () {
if (typeRealty.options[typeRealty.selectedIndex].value === 'Лачуга') {
priceRealty.value = '0';
}
if (typeRealty.options[typeRealty.selectedIndex].value === 'Дворец') {
priceRealty.value = '10000';
}
if (typeRealty.options[typeRealty.selectedIndex].value === 'Квартира') {
priceRealty.value = '1000';
}
};
var roomNumber = document.querySelector('#room_number');
var capacityNumber = document.querySelector('#capacity');
roomNumber.onchange = function () {
if (roomNumber.options.selectedIndex === 0) {
capacityNumber.options.selectedIndex = 1;
}
if (roomNumber.options.selectedIndex === 1) {
capacityNumber.options.selectedIndex = 0;
}
if (roomNumber.options.selectedIndex === 2) {
capacityNumber.options.selectedIndex = 0;
}
};
var formContent = document.querySelector('.notice__form');
var formSubmit = document.querySelector('.form__submit');
formSubmit.addEventListener('click', function () {
formContent.reset();
});
}
setupMap();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment