-
Notifications
You must be signed in to change notification settings - Fork 0
Js 2 les 2 revise #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zagidulin
wants to merge
2
commits into
master
Choose a base branch
from
JS_2_les_2_revise
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| 'use strict'; | ||
|
|
||
|
|
||
| const products = [ | ||
| { title: 'Rollerblade Twister Edge', price: 150, link: 'twister_edge' }, | ||
| { title: 'K2 Alexis 80 PRO', price: 50, link: 'k2_alexis_80_pro' }, | ||
| { title: 'FRX 80', price: 350, link: 'seba_frx_80' }, | ||
| { title: 'Rollerblade Macroblade', price: 250, link: 'rollerblade_macroblade_84W' }, | ||
| ]; | ||
|
|
||
| const shopCart = []; | ||
|
|
||
| class ProductItem { | ||
| constructor(title, price, link) { | ||
| this.title = title; | ||
| this.price = price; | ||
| this.link = link; | ||
| } | ||
|
|
||
| render() { | ||
| return `<div class="product_preview"> | ||
| <div class="preview_image"> | ||
| <a href="catalog/${this.link}.html"> | ||
| <img src="image/${this.link}.jpg" alt="" width="120" height="120"> | ||
| </a> | ||
| </div><br> | ||
| <a href="catalog/${this.link}.html">${this.title}</a> | ||
| <p><span class="price">${this.price}</span> руб.</p> | ||
| <button>buy</button> | ||
| </div>`; | ||
| } | ||
| } | ||
|
|
||
|
|
||
| class ProductsList { | ||
| constructor() { | ||
| this.products = []; | ||
| this.filteredProducts = []; | ||
| } | ||
|
|
||
| _getProducts() { | ||
| this.products = products; | ||
| this.filteredProducts = this.products; | ||
| console.log('this.filteredProducts', this.filteredProducts) | ||
| } | ||
|
|
||
| render(list) { | ||
| /* В разборе д/з предложили убрать блок if ниже и всегда рендерить | ||
| this.filteredProducts. Но в этом блоке, если не было фильтрации и методу render() | ||
| не передан отфильтрованный список, выполняется получение списка товаров (this._getProducts()). | ||
| И render() без аргумента вызывается при загрузке/перезагрузке страницы. Таким образом, если | ||
| убрать блок условия, то вообще не будет получен список товаров и фильтровать тоже будет нечего. | ||
| Можно, кончено, в main.js вызывать _getProducts() отдельно при загрузке странице, но предполагается, | ||
| что это приватный метод (передалаю в #). | ||
| При фильтрации в render() можно было бы передавать true, например, тогда при отсутствии соответствия | ||
| поиску выводилась бы пустая страница, но в момент выполнения задания решил, что если нет удовлетворяющих | ||
| условиям поиска товаров, то будет выводиться весь каталог. | ||
| */ | ||
| if (list && list.length > 0) { | ||
| console.log(list); | ||
| } else { | ||
| this._getProducts(); | ||
| } | ||
|
|
||
| let html = ''; | ||
|
|
||
| this.filteredProducts.forEach(({ title, price, link }) => { | ||
| const productItem = new ProductItem(title, price, link); | ||
| html += productItem.render(); | ||
| }); | ||
|
|
||
| document.querySelector('.catalog').innerHTML = html; | ||
| } | ||
|
|
||
| total() { | ||
| let total = 0; | ||
| this.products.forEach(({ price }) => { | ||
| total += price; | ||
| }); | ||
|
|
||
| console.log('Сумма всех цен: ', total); | ||
| } | ||
|
|
||
| filterProducts(value) { | ||
| const regexp = new RegExp(value, 'i'); | ||
| this.filteredProducts = this.products.filter(product => regexp.test(product.title)); | ||
| this.render(this.filteredProducts); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| 'use strict'; | ||
|
|
||
| window.addEventListener('load', () => { | ||
| const catalogList = new ProductsList(); | ||
| const shopingCart = new BasketList(); | ||
|
|
||
| catalogList.render(); | ||
|
|
||
| let catalog = document.querySelector('.catalog'); | ||
| let basket = document.querySelector('.cart-button'); | ||
| let closeBasket = document.querySelector('.close'); | ||
| let findValue = document.querySelector('.products_filter'); | ||
| let findButton = document.getElementById('find'); | ||
|
|
||
|
|
||
| catalog.addEventListener('click', (event) => { | ||
| console.log(event.target.innerText); | ||
| if (event.target.innerText == 'buy') { | ||
| let name = event.target.parentNode.childNodes[4].innerText; | ||
| let price = +event.target.parentNode.childNodes[6].childNodes[0].innerText; | ||
| let image = event.target.parentNode.childNodes[1].childNodes[1].childNodes[1].outerHTML; | ||
| shopingCart.add(name, price, image); | ||
| } | ||
| }); | ||
|
|
||
| basket.addEventListener('click', (event) => { | ||
| shopingCart.render(); | ||
| shopingCart.toggle(); | ||
| }); | ||
|
|
||
| closeBasket.addEventListener('click', (event) => { | ||
| shopingCart.toggle(); | ||
| }); | ||
|
|
||
| findButton.addEventListener('click', () => { | ||
| catalogList.filterProducts(findValue.value); | ||
| }); | ||
|
|
||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, это тоже справедливое замечание!
В целом, на маленьких проектах такая связка методов допустима. Но в больших проектах с большим количеством кода имеет смысл пересмотреть архитектуру таким образом, чтобы получение данных и рендер не были связаны и могли бы вызываться по отдельности. А так, опять же, хвалю за внимательность :)