상세 컨텐츠

본문 제목

budgety app 5편

JavaScript

by nata_developer 2020. 9. 15. 17:55

본문

var budgetController = (function () {
  var Expense = function (id, description, value) {
    this.id = id;
    this.description = description;
    this.value = value;
  };

  var Income = function (id, description, value) {
    this.id = id;
    this.description = description;
    this.value = value;
  };

  var calculateTotal = function(type) {
      var sum = 0;
    
      data.allItems[type].forEach(function(cur) {
        sum += cur.value
      })

      data.totals[type] = sum
  }

  var data = {
    allItems: {
      exp: [],
      inc: [],
    },
    totals: {
      exp: 0,
      inc: 0,
    },
    budget: 0,
    percentage: -1
  };

  return {
    addItem: function (type, des, val) {
      var newItem;

      if (data.allItems[type].length > 0) {
        ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
      } else {
        ID = 0;
      }

      if (type === "exp") {
        newItem = new Expense(ID, des, val);
      } else if (type === "inc") {
        newItem = new Income(ID, des, val);
      }

      data.allItems[type].push(newItem);

      return newItem;
    },

    deleteItem: function(type, id) {
      var id, index

      ids = data.allItems[type].map(function(current) {
        return current.id
      })

      index = ids.indexOf(id)

      if(index !== -1) {
        data.allItems[type].splice(index, 1)
      }
    },

    calculateBudget: function() {
        calculateTotal("exp")

        calculateTotal("inc")

        data.budget = data.totals.inc - data.totals.exp
        
        if(data.totals.inc > 0) {
            data.percentage = Math.round((data.totals.exp / data.totals.inc) * 100)
        } else {
            data.percentage = - 1;
        }
    },

    getBudget: function() {
        return {
            budget: data.budget,
            totalInc: data.totals.inc,
            totalExp: data.totals.exp,
            percentage: data.percentage,
        }
    },

    testing: function () {
      console.log(data);
    },
  };
})();

var UIController = (function () {
  var DOMstrings = {
    inputType: ".add__type",
    inputDescription: ".add__description",
    inputValue: ".add__value",
    inputBtn: ".add__btn",
    incomeContainer: ".income__list",
    expensesContainer: ".expenses__list",
    budgetLabel: ".budget__value",
    incomeLabel: ".budget__income--value",
    expensesLabel: ".budget__expenses--value",
    percentageLabel: ".budget__expenses--percentage",
    container: ".container"
  };
  return {
    getInput: function () {
      return {
        type: document.querySelector(DOMstrings.inputType).value,
        description: document.querySelector(DOMstrings.inputDescription).value,
        value: parseFloat(document.querySelector(DOMstrings.inputValue).value),
      };
    },

    addListItem: function (obj, type) {
      var html, newHtml, element;

      if (type === "inc") {
        element = DOMstrings.incomeContainer;

        html =
          '<div class="item clearfix" id="inc-%id%"> <div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
      } else if (type === "exp") {
        element = DOMstrings.expensesContainer;

        html =
          '<div class="item clearfix" id="exp-%id%"><div class="item__description">%description%</div><div class="right clearfix"><div class="item__value">%value%</div><div class="item__percentage">21%</div><div class="item__delete"><button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button></div></div></div>';
      }

      newHtml = html.replace("%id%", obj.id);
      newHtml = newHtml.replace("%description%", obj.description);
      newHtml = newHtml.replace("%value%", obj.value);

      document.querySelector(element).insertAdjacentHTML("beforeend", newHtml);
    },

    deleteListItem: function(selectorID) {
      var el = document.getElementById(selectorID)
      el.parentNode.removeChild(el)
    },

    clearFields: function() {
        var fields, fieldsArr;

        fields = document.querySelectorAll(DOMstrings.inputDescription + ", " + DOMstrings.inputValue)
    
        fieldsArr = Array.prototype.slice.call(fields)
    
        fieldsArr.forEach(function(current, index, array) {
            current.value = "";

        })

        fieldsArr[0].focus()
    },

    displayBudget: function(obj) {
        document.querySelector(DOMstrings.budgetLabel).textContent = obj.budget;
        document.querySelector(DOMstrings.incomeLabel).textContent = obj.totalInc;
        document.querySelector(DOMstrings.expensesLabel).textContent = obj.toalExp;
    
        if(obj.percentage > 0) {
            document.querySelector(DOMstrings.percentageLabel).textContent = obj.percentage + "%";
        } else {
            document.querySelector(DOMstrings.percentageLabel).textContent = "---";
        }
    },

    getDOMstrings: function () {
      return DOMstrings;
    },
  };
})();

var controller = (function (budgetCtrl, UICtrl) {
  var setupEventListeners = function () {
    var DOM = UICtrl.getDOMstrings();

    document.querySelector(DOM.inputBtn).addEventListener("click", ctrlAddItem);

    document.addEventListener("keypress", function (event) {
      if (event.key === 13) {
        ctrlAddItem();
      }
    });
    document.querySelector(DOM.container).addEventListener("click", ctrlDeleteItem)
  };

  var updateBudget = function() {
    budgetCtrl.calculateBudget();

    var budget = budgetCtrl.getBudget()

    UICtrl.displayBudget(budget)

  }

  var ctrlAddItem = function () {
    var input, newItem;

    input = UICtrl.getInput();

    if(input.description !== "" && !isNaN(input.value) && input.value > 0) {
       
        newItem = budgetCtrl.addItem(input.type, input.description, input.value);
  
        UICtrl.addListItem(newItem, input.type)
    
        UICtrl.clearFields()
    
        updateBudget()

    }
};

var ctrlDeleteItem = function(event) {
  var itemID;

  itemID = event.target.parentNode.parentNode.parentNode.parentNode.id

  if(itemID) {
    splitID = itemID.split("-")
    type = splitID[0]
    ID = parseInt(splitID[1])

    budgetCtrl.deleteItem(type, ID)

    UICtrl.deleteListItem(itemID)

    updateBudget()
  }
}

  return {
    init: function () {
      console.log("Application has started");
      UICtrl.displayBudget({
          budget: 0,
          totalInc: 0,
          totalExp: 0,
          percentage: -1
      })
      setupEventListeners();
    },
  };
})(budgetController, UIController);

controller.init();

deleteItem

 

data에 있는 allItems의 id를 ids 변수에 담고,

 

ids의 값에서 index를 추출한다.

 

index 값이 -1이 아니라면,

 

data.allItems의 값을 삭제한다.

 

deleteListItem

 

selectorID의 부모요소에 접근하여 자식요소를 제거한다.

 

ctrlDeleteItem

 

itemID에 최상위 노드를 할당하고,  splitID, type, id를 분리하여 재 할당한다.

 

그 후  UICtrl.deleteListItem에  itemID를

 

할당하여 UI에서 아이템을 삭제한다.

'JavaScript' 카테고리의 다른 글

budgety app 5편  (0) 2020.09.15
budgety app 4편  (0) 2020.09.15
budgety app 3편  (0) 2020.09.15
budgety app 2편  (0) 2020.09.15
budgety app 1편  (0) 2020.09.15

관련글 더보기