상세 컨텐츠

본문 제목

budgety app 5편

JavaScript

by nata_developer 2020. 9. 15. 17:10

본문

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;
    },

    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"
  };
  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);
    },

    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 () {
      if (event.keyCode === 13 || event.which === 12) {
        ctrlAddItem();
      }
    });
  };

  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()

    }
};

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

controller.init();

displayBudget

 

data에 저장된 값을 budget, totalInc, totalExp, percentage element의

 

textContent에 할당한다.

 

UICtrl.displayBudget(budget)

 

updateBudget 메써드에 넣어 갱신되는 값을 할당한다.

 

    UICtrl.displayBudget({

          budget: 0,

          totalInc: 0,

          totalExp: 0,

          percentage: -1

      })

 

init에서 displayBudget의 기본 값을 설정한다.

'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

관련글 더보기