JSFiddle - React, Tailwind, and code Playground
by kashesandr
HTML
<div id="main">
</div>
<div id="price">
</div>
<a href="javascript:void(0)" id="add">Add item</a>
JavaScript
// Define like a ~class
var PriceCalculator = function(priceElement) {
this.priceElement = priceElement;//DOM элемент создаётся
this.items = [];
//
this.TYPE_TO_PRICE_MAP = {//здесь задается товар
a: 1,
b: 2,
c: 3
};
this.ITEM = {
types: ['a', 'b', 'c'],// тип или товар
colors: ['red', 'green', 'blue'],// цвет
counts: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]// количество
}
// item example:
// { types: [], colors: [], counts: [] }
};
//добавляем item
PriceCalculator.prototype.add = function() {
this.items.push(this.ITEM);
};
// todo: change to use index instead of item
//удаляем товар
PriceCalculator.prototype.remove = function(item) {
index = null;
for (var i = 0; i < this.items.length - 1; i++)
if (this._areDeepEqual(this.items[i], item))
index = i;
if (index == null) return;
this.items.splice(index, 1); // delete
};
//глубокое сравнение двух объектов
PriceCalculator.prototype._areDeepEqual = function(item1, item2) {
return JSON.stringify(item1) === JSON.stringify(item2);
};
//получить цену товара
PriceCalculator.prototype.getItemPrice = function(item) {
var type = item.typesSelected;
var count = item.countsSelected;
var price = this.TYPE_TO_PRICE_MAP[type] || 0;
var result = price * count;
return result;
};
PriceCalculator.prototype.calculate = function() {
var _this = this;
var pricesArray = this.items.map(function(_item) {
var price = _this.getItemPrice(_item);
return price;
})
var result = pricesArray.reduce(function(a, b) {
return a + b;
}, 0);
this.priceElement.innerHTML = result;
};
//заполнение select optionами
PriceCalculator.prototype.fillOptions = function(selectElemnet, options){
for (var i = 0; i < options.length; i++) {
option = document.createElement('option');
option.setAttribute('value', options[i]);
option.appendChild(document.createTextNode(options[i]));
selectElemnet.appendChild(option);
}
}
PriceCalculator.prototype.render =...