Synopsis
We have the Controller that acts as the middleman between a data controller (budgetCtrl) and UI controller (UICtrl).
In the Controller, we declare click events for user actions. Once that click event happens, the Controller takes in data and stores it into a data structure.
In the case of adding an item, the Controller takes data from the DOM by using function querySelector and gives it to budgetCtrl to store and manipulate.
Once it finishes, it calls budgetCtrl’s related getXXXXXXX() function and gets the data it needs to display. It passes that data to the UICtrl to be displayed.
BudgetController
The budget controller holds data that stores expenses and incomes.
Specifically, it will store individual expenses and incomes via array:
1 2 3 4 5 6 |
var data = { allItems: { exp: [], inc: [], }, } |
It then stores a total for all the expenses and incomes.
It also has:
Leftover Budget – incomes – expenses
total percentage – expenses / income
1 2 3 4 5 6 7 8 9 |
var data = { total: { exp: 0, inc: 0 }, budget: 0, totalPercentage: 0 } |
And thus, our budgetController keeps track and hold data. Naturally, it will have functions that manipulate these data.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var budgetController = (function () { var data = { allItems: { exp: [], inc: [], }, total: { exp: 0, inc: 0 }, budget: 0, totalPercentage: 0 } return { addItem: function(type, desc, value) { ... }, ... } })(); |
Let’s look at the simple functionality of adding an item.
On the data side, we want three things:
– type (income or expense)
– description of the income or expense
– value of the income or expense
Then we simply use the string ‘inc’ or ‘exp to act as the property name inc/exp.
Thus we are able to dynamically use arrays data.allItems.inc or data.allItems.exp simply by using data.allItems[type] where type is “inc” or “exp”.
This is how we get the array we want to use.
The idea is for adding items is that we append it to the end.
So we first have to assign an ID for the item. The ID is simply the index of the next available element.
For example, if the array is empty, then the ID for our item should be 0. If the index of the next available item is 2, then the ID we assign to our item should be 2:
1 |
let ID = (lastIndex < 0) ? 0 : arr[lastIndex].id + 1 |
We then create a newItem according to the type. If its a ‘exp’, we simply create a new Expense. If its ‘inc’, then we create income object.
After that, we stick the item into the respective array.
1 2 3 4 5 6 7 8 |
addItem: function(type, desc, value) { let lastIndex = data.allItems[type].length - 1; let arr = data.allItems[type]; let ID = (lastIndex < 0) ? 0 : arr[lastIndex].id + 1 var newItem = (type==='exp') ? new Expense(ID, desc, value) : new Income(ID, desc, value); data.allItems[type].push(newItem); return newItem; }, |
Controller
In the controller, we first set up some basic key press features for when user enters their data.
We do this in setupEventListener function.
We add a click event listener to when the user clicks on the button which has id/class of DOM.INPUT_BUTTON.
In our case, the button has class ‘.add__button’. When the element with that class is clicked, we call on ctrlAddItem.
1 2 3 4 5 6 7 8 9 10 11 12 |
var controller = (function(budgetCtrl, UICtrl) { var setupEventListener = function() { var DOM = UICtrl.getDOMStrings(); document.querySelector(DOM.INPUT_BUTTON).addEventListener('click', ctrlAddItem); document.addEventListener('keypress', function(event) { if (event.keyCode === 13 || event.which === 13) { // return key ctrlAddItem(); } }) document.querySelector(DOM.CONTAINER).addEventListener('click', ctrlDeleteItem); } |
We store the DOM elements’ classes and ids strings into an object literal.
1 2 3 4 5 |
var DOMStrings = { INPUT_TYPE: '.add__type', INPUT_DESCRIPTION: '.add__description', INPUT_VALUE: '.add__value', } |
By using querySelector along with these macros, querySelector will go into the DOM, find the elements with those strings as id/class and retrieve data.
So continuing on, when the button was clicked, it executes ctrlAddItem. In ctrlAddItem, we first get data from three elements and put them into an object called ‘input’.
The three data is type, description, and value, which represents the item you are inserting.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function ctrlAddItem() { // get input field let input = UICtrl.getInput(); if (input.description !== "" && !isNaN(input.value) && input.value > 0 ) { // add item to budget controller var newItem = budgetCtrl.addItem(input.selectedType, input.description, input.value); // add item to UI UICtrl.addListItem(newItem, input.selectedType); UICtrl.clearField(); updateBudget(); updatePercentages(); } } |
Then we do an error check for the data stored in object input. If everything checks through then we have enough information to feed our budgetCtrl’s addItem function.
After adding the data into our budgetCtrl (data container), we then have our UI controller add it into our UI.
Then we clear fields.
Notice the last updateBudget and updatePercentages.
Once we have new data stored in our arrays, we need to call those functions to calculate what we need.
updateBudget
We have access to budgetCtrl and UICtrl. So the main idea is for budgetCtrl to calculateitself. Then get the data we want, i.e budget.
Once we have the budget data, we just pass to the UICtrl to be displayed.
1 2 3 4 5 |
function updateBudget() { budgetCtrl.calculateBudget(); let budget = budgetCtrl.getBudget(); UICtrl.displayBudget(budget) } |
updatePercentages
Same goes for updating percentages. The main idea is that we calculate data in budgetCtrl, and then using getXXXXXX() we get the needed data from budgetCtrl.
We pass this data into the UICtrl, which then takes care of displaying the changed data onto the UI.
1 2 3 4 5 6 7 8 9 10 |
function updatePercentages() { // 1) calculate percentages budgetCtrl.calculatePercentages(); // 2) read from budget controller let arrOfPercentages = budgetCtrl.getPercentages(); // 3 ) update user interface UICtrl.displayAllPercentage(arrOfPercentages); } |
Notice updatePercentages operates the same way. We first have budgetCtrl, which keeps track of all our data, to calculate what it needs. Specifically the percentages of the expenses in relation to the income. We then extract the percentage array from budgetCtrl.
Using that array, we insert it into the UI controller to be displayed.
UIController
The data gets calculated many times in budgetCtrl, and we must make sure that change gets reflected in our UI. The UI controller does exactly this by making use of document.querySelector A LOT.
querySelector takes an argument of a string which represents the element’s class or id name. In our case, for the type, we want to get what was selected.
1 2 3 4 |
<select class="add__type"> <option value="inc" selected="">+</option> <option value="exp">-</option> </select> |
We first create an object to keep tract of these classes and ids.
Notice class add__type. We will store it as a macro in DOMStrings object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
var UIController = (function() { // private var DOMStrings = { INPUT_TYPE: '.add__type', } return { getInput: function() { return { selectedType: document.querySelector(DOMStrings.INPUT_TYPE).value, description: document.querySelector(DOMStrings.INPUT_DESCRIPTION).value, value: parseFloat(document.querySelector(DOMStrings.INPUT_VALUE).value), } }, })(); |
We see that we have a select control in HTML. When the user makes a selection on the web page, the string ‘+’ or ‘-‘ will be given to the select tag. By using querySelector function to retrieve that value, we can then store it into a property called selectedType. Same goes for the description and amount.
Now we want to add this item to the UI. We do this by first getting two objects. First is the parameter type so we know whether to add the data to the income div or expense div.
When we know whether to add expense or income, we can safely get the parameter obj and literally just do a data dump.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
addListItem: function(obj, type) { // create HTML string with placeholder text var html, element; if (type === 'inc') { element = DOMStrings.INCOME_CONTAINER; html = `<div class="item clearfix" id="inc-${obj.id}"> <div class="item__description">${obj.description}</div> <div class="right clearfix"> <div class="item__value">+ ${obj.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.EXPENSE_CONTAINER; html = `<div class="item clearfix" id="exp-${obj.id}"> <div class="item__description">${obj.description}</div> <div class="right clearfix"> <div class="item__value">- ${obj.val}</></div> <div class="item__percentage"></div> <div class="item__delete"> <button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button> </div> </div> </div>` } document.querySelector(element).insertAdjacentHTML('beforeend', html) } |
Full Source code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
var budgetController = (function () { let Expense = function(id, description, value) { this.id = id; this.description = description; this.value = value; this.percentage = -1; } Expense.prototype.calcPercentage = function(totalIncome) { if (totalIncome > 0) this.percentage = (this.value / totalIncome) * 100 else this.percentage = -1; } Expense.prototype.getPercentage = function() { return this.percentage; } let Income = function(id, description, value) { this.id = id; this.description = description; this.value = value; } let calculateTotal = function(type) { let dataArr = data.allItems[type]; let total = 0; for (let i = 0; i < dataArr.length; i++) { total = total + dataArr[i].value; } data.total[type] = total; return total; } var data = { allItems: { exp: [], inc: [], }, total: { exp: 0, inc: 0 }, budget: 0, totalPercentage: 0 } return { addItem: function(type, desc, value) { let lastIndex = data.allItems[type].length - 1; let arr = data.allItems[type]; let ID = (lastIndex < 0) ? 0 : arr[lastIndex].id + 1 var newItem = (type==='exp') ? new Expense(ID, desc, value) : new Income(ID, desc, value); data.allItems[type].push(newItem); return newItem; }, deleteItem: function(type, ayeDee) { console.log(`budgetController - deleteItem: type ${type}, id ${ayeDee}`); let dataArr = data.allItems[type]; let indexToDelete = -1; for ( let i = 0; i < dataArr.length; i++) { let item = dataArr[i]; if (item.id === ayeDee) { indexToDelete = i; break; } } if (indexToDelete !== -1) { dataArr.splice(indexToDelete, 1); } else { console.log(`item with id ${ayeDee} not foud`) } }, calculateBudget: function() { calculateTotal('exp'); calculateTotal('inc'); data.budget = data.total.inc - data.total.exp; if (data.total.inc > 0 && data.total.exp > 0) { data.totalPercentage = (data.total.exp / data.total.inc) * 100; } else if (data.total.exp > 0 && data.total.inc == 0) { data.totalPercentage = 100; } else if (data.total.exp == 0 && data.total.inc > 0) { data.totalPercentage = 0; } }, calculatePercentages: function() { let numOfExpenses = data.allItems.exp.length; let arrOfExpenses = data.allItems.exp; for (let i = 0; i < numOfExpenses; i++) { let expense = arrOfExpenses[i]; if (expense instanceof Expense && typeof expense.calcPercentage === 'function') { expense.calcPercentage(data.total.inc); } } }, getPercentages: function() { var allPerc = data.allItems.exp.map( function(expObj) { return expObj.getPercentage(); }); return allPerc; }, getBudget: function() { return { budget: data.budget, totalIncome: data.total.inc, totalExpense: data.total.exp, totalPercentage: data.totalPercentage } } } })(); var UIController = (function() { // private var DOMStrings = { INPUT_TYPE: '.add__type', INPUT_DESCRIPTION: '.add__description', INPUT_VALUE: '.add__value', INPUT_BUTTON: '.add__btn', INCOME_CONTAINER: '.income__list', EXPENSE_CONTAINER: '.expenses__list', BUDGET_LABEL: '.budget__value', INCOME_LABEL: '.budget__income--value', EXPENSES_LABEL: '.budget__expenses--value', PERCENTAGE_LABEL: '.budget__expenses--percentage', CONTAINER: '.container', ITEM_PERCENTAGE_LABEL: '.item__percentage', DATE_LABEL: '.budget__title--month', } var monthStrings = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] return { getInput: function() { return { // value come from <option value='XXXXXXX'>....</option> // user selects as expense/income selectedType: document.querySelector(DOMStrings.INPUT_TYPE).value, // description of the expense/income description: document.querySelector(DOMStrings.INPUT_DESCRIPTION).value, // the value of the expense/income value: parseFloat(document.querySelector(DOMStrings.INPUT_VALUE).value), } }, displayAllPercentage: function(percentages) { let fields = document.querySelectorAll(DOMStrings.ITEM_PERCENTAGE_LABEL); console.log(fields) // declaration of var, takes on function expression var nodeListForEach = function(list, callback) { for( let i = 0; i < list.length; i++) { callback(list[i], i); } }; // execution nodeListForEach(fields, function(current, index){ if (percentages[index] > 0) current.textContent = percentages[index] + '%'; else current.textContent = '---'; }); }, displayMonth: function() { let d = new Date(); year = d.getFullYear(); month = d.getMonth(); document.querySelector(DOMStrings.DATE_LABEL).textContent = monthStrings[month-1] + ', ' + year; }, // expose private DOMStrings literal object to public getDOMStrings: function() { return DOMStrings; }, addListItem: function(obj, type) { // create HTML string with placeholder text var html, element; if (type === 'inc') { element = DOMStrings.INCOME_CONTAINER; html = `<div class="item clearfix" id="inc-${obj.id}"> <div class="item__description">${obj.description}</div> <div class="right clearfix"> <div class="item__value">+ ${obj.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.EXPENSE_CONTAINER; html = `<div class="item clearfix" id="exp-${obj.id}"> <div class="item__description">${obj.description}</div> <div class="right clearfix"> <div class="item__value">- ${obj.value}</div> <div class="item__percentage"></div> <div class="item__delete"> <button class="item__delete--btn"><i class="ion-ios-close-outline"></i></button> </div> </div> </div>`; } else { } // insert html into dom document.querySelector(element).insertAdjacentHTML('beforeend', html) }, deleteItemElement: function(selector) { console.log(`deleting item with id ${selector}`) let ele = document.querySelector('#'+selector); console.log(ele) if (ele) ele.parentNode.removeChild(ele); }, clearField: function() { document.querySelector(DOMStrings.INPUT_DESCRIPTION).value = ''; document.querySelector(DOMStrings.INPUT_VALUE).value = ''; document.querySelector(DOMStrings.INPUT_DESCRIPTION).focus(); }, displayBudget: function(data) { document.querySelector(DOMStrings.BUDGET_LABEL).textContent = data.budget; document.querySelector(DOMStrings.INCOME_LABEL).textContent = data.totalIncome; document.querySelector(DOMStrings.EXPENSES_LABEL).textContent = data.totalExpense; let formattedPercentage = data.totalPercentage > 0 ? data.totalPercentage.toFixed(2) : 0; console.log(formattedPercentage); document.querySelector(DOMStrings.PERCENTAGE_LABEL).textContent = formattedPercentage + ' %'; } } })(); var controller = (function(budgetCtrl, UICtrl) { var setupEventListener = function() { var DOM = UICtrl.getDOMStrings(); document.querySelector(DOM.INPUT_BUTTON).addEventListener('click', ctrlAddItem); document.addEventListener('keypress', function(event) { if (event.keyCode === 13 || event.which === 13) { // return key ctrlAddItem(); } }) document.querySelector(DOM.CONTAINER).addEventListener('click', ctrlDeleteItem); } function updateBudget() { budgetCtrl.calculateBudget(); let budget = budgetCtrl.getBudget(); UICtrl.displayBudget(budget) } function ctrlDeleteItem(event) { console.log('--- an event came from ---'); // its ok for us to hardcode the finding of the id because when we add // an expense or income, our html is hardcoded. // This ensures that clicking on an x button will get us the id for that particular // list item html let itemID = event.target.parentNode.parentNode.parentNode.parentNode.id; if (itemID) { let arr = itemID.split('-'); let type = arr[0]; let ayeDee = arr[1]; // delete ite from our data struvture budgetCtrl.deleteItem(type, parseFloat(ayeDee)); // delete item from UI UICtrl.deleteItemElement(itemID); // update and show new budget updateBudget(); } } function updatePercentages() { // 1) calculate percentages budgetCtrl.calculatePercentages(); // 2) read from budget controller let arrOfPercentages = budgetCtrl.getPercentages(); // 3 ) update user interface UICtrl.displayAllPercentage(arrOfPercentages); } function ctrlAddItem() { // get input field let input = UICtrl.getInput(); if (input.description !== "" && !isNaN(input.value) && input.value > 0 ) { // add item to budget controller var newItem = budgetCtrl.addItem(input.selectedType, input.description, input.value); // add item to UI UICtrl.addListItem(newItem, input.selectedType); UICtrl.clearField(); updateBudget(); updatePercentages(); } } return { init: function() { console.log('Application has started... √'); setupEventListener(); UICtrl.displayMonth(); } } })(budgetController, UIController); controller.init(); |