为什么addEventListener不调用我的addItem函数?

时间:2019-01-09 20:01:08

标签: javascript addeventlistener

前一阵子工作正常,但现在不是。控制台也没有给出任何错误。我添加了 console.log 字符串

console.log("You can't reach me!!");

跟踪执行流程,但是当放置在 addItem 函数中并单击 +按钮时,字符串停止显示,这使我怀疑未调用addItem 函数。

eventListener:

document.querySelector(".button").addEventListener('click', addItem);

addItem函数:

let controller = (function(budgetCtrl, uiCtrl){

let input,newItem;

let addItem = function(){
    // 1. Get the field input data
    console.log("You can't reach me!!");
    input = uiCtrl.getInput();
    if(input.description !="" && !isNaN(input.value) && input.value > 0){

        // 2. Add the item to the budget budgetController
        newItem = budgetCtrl.addItem(input.type, input.description, input.value);
        // 3. Add the item to the UI
        uiCtrl.addListItem(newItem, input.type);

        // 4. Clear the fieldsArray
        uiCtrl.clearFields();
        // 5.Calculate and update the budget
        updateBudget();
    }


}

我在下面添加了完整的代码,以备不时之需。

html文件

<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>Budget App</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div class="top">
            <div class="total">money</div>
            <div class="green">
                <span class="left">INCOME $ </span><span class="right, income-budget">+ 4,300.00</span>
            </div>
            <div class="red">
                <span class="left">EXPENSES $ </span><span class="right, expense-budget">- 1954.46</span>
            </div>
        </div>
        <div class="middle">
            <select class="operation">
                <option value="exp">-</option>
                <option selected value="inc">+</option>
            </select>
            <input class="description" type="text"  placeholder="Add description">
            <input class="value" type="number"  placeholder="value" min ="0">
            <button class="button">+</button>
        </div>
        <div class="bottom">
            <div class="bottom-left">
                <h3>INCOME</h3>
                <div class="income-list">
                    <!--
                    <div id="income-0" class="inline">
                        <div class="item-description">Salary</div>
                        <div class="item-value">+2,100.00</div>
                        <button type="button">X</button>
                    </div>
                    <!-->

                </div>
            </div>
            <div class="bottom-right">
                <h3>EXPENSES</h3>
                <div class="expense-list">
                <!--
                    <div id="expense-0" class="inline">
                        <div class="item-description">Bought car</div>
                        <div class="item-value">-2,100.00</div>
                        <button type="button">X</button>
                    </div>
                <!-->

                </div>
            </div>
        </div>
        <script src="app.js" charset="utf-8"></script>
    </body>
</html>

如果您需要整个javascript文件

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

    let calculateTotal = function(type){
        let sum = 0;
        data.allItems[type].forEach(function(current){
            sum += current.value;
        });
        data.totals[type] = sum;
    };

    let data = {
        allItems: {
            exp:[],
            inc:[]
        },
        totals: {
            exp: 0,
            inc:0
        },
        budget: 0
    }
    // Public method that allows other modules to add a new item to the data struc
    return{
        addItem: function(type, description, value){
            let newItem, ID;

            // Create a new ID
            if (data.allItems[type].length > 0){
                // I don't understand the .id in the following line of code
                ID = data.allItems[type][data.allItems[type].length - 1].id + 1;
            } else{
                ID = 0;
            }

            // Create new item based on 'inc' or 'exp'
            if(type === 'exp'){
                newItem = new Expense(ID, description, value);
            }
            else if( type === 'inc'){
                newItem = new Income(ID, description, value);
            }

            // Add item to the data structure
            data.allItems[type].push(newItem);
            // Return the new element
            return newItem;
        },

        calculateBudget: function(){
                // calculate total income and expenses
                calculateTotal('exp');
                calculateTotal('inc');
                // Calculate the budget: income - EXPENSES
                data.budget = data.totals.inc - data.totals.exp;
        },

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

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

let uiController = (function(){

    return{
        getInput: function(){
            return{
                type: document.querySelector('.operation').value,
                description: document.querySelector('.description').value,
                value: parseFloat(document.querySelector('.value').value)
            };
        },
        addListItem: function(obj, type){
            let HTML, listType;
            // Create htML string with placeholder text

            if(type === 'inc'){
                element = '.income-list';
                listType = 'income';
            }else{
                element = '.expense-list';
                listType = 'expense';
            }
            HTML = '<div id="%listType%-%id%" class="inline">' +
                        '<div class="item-description">%description%</div>' +
                        '<div class="item-value">%value%</div>' +
                        '<button type="button">X</button>' +
                    '</div>'
            // Replace the placeholder text with the actual data
            HTML = HTML.replace('%listType%', listType)
            HTML = HTML.replace('%id%', obj.id);
            HTML = HTML.replace('%description%', obj.description);
            HTML = HTML.replace('%value%', obj.value);

            // Insert the htML into the DOM
            document.querySelector(element).insertAdjacentHTML('beforeend', HTML);
        },
        clearFields: function(){
            let fields, fieldsArray;
            // querySelectorAll returns a list not an array
            fields = document.querySelectorAll('.description, .value');
            fieldsArray = Array.prototype.slice.call(fields);

            fieldsArray.forEach(function(current, index, array){
                current.value ="";
            });
            // Sets focus to the descriptions field
            fieldsArray[0].focus();
        },

        displayBudget: function(object){
            document.querySelector('.total').innerHTML = object.budget;
            document.querySelector('.income-budget').innerHTML = object.totalInc;
            document.querySelector('.expense-budget').innerHTML = object.totalExp;
        }
    }

})();

let controller = (function(budgetCtrl, uiCtrl){

    let input,newItem;

    let addItem = function(){
        // 1. Get the field input data
        console.log("You can't reach me!!");
        input = uiCtrl.getInput();
        if(input.description !="" && !isNaN(input.value) && input.value > 0){

            // 2. Add the item to the budget budgetController
            newItem = budgetCtrl.addItem(input.type, input.description, input.value);
            // 3. Add the item to the UI
            uiCtrl.addListItem(newItem, input.type);

            // 4. Clear the fieldsArray
            uiCtrl.clearFields();
            // 5.Calculate and update the budget
            updateBudget();
        }


    }

    let updateBudget = function(){
        // 1. Calculate the budgetCtrl
        budgetCtrl.calculateBudget();
        // 2. Return the budget
        let budget = budgetCtrl.getBudget();
        // 3. Display the budget on the UI
        uiCtrl.displayBudget(budget);
    }

    //let ctrlDeleteItem = function(event){
    //        console.log(event.target);
    //}

    let enterKey = function(event){
        if(event.keyCode === 13 || event.which === 13){// older browers use which
        addItem();
        }
    }

    return {
        init: function(){
            const budget =  {budget: 0, totalInc:0, totalExp:0};
            uiCtrl.displayBudget(budget);
        }
    };

    document.querySelector(".button").addEventListener('click', addItem);
    document.addEventListener('keypress', enterKey);
    document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);


})(budgetController, uiController);

controller.init();

1 个答案:

答案 0 :(得分:4)

您的代码永远不会到达addEventListener,因为您之前有return。这几乎是无法访问的代码。

return {
    init: function(){
        const budget =  {budget: 0, totalInc:0, totalExp:0};
        uiCtrl.displayBudget(budget);
    }
};
//unreachable..
document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);

解决方案

用您的return切换无法访问的代码。

document.querySelector(".button").addEventListener('click', addItem);
document.addEventListener('keypress', enterKey);
document.querySelector('.bottom').addEventListener('click', ctrlDeleteItem);

return {
    init: function(){
        const budget =  {budget: 0, totalInc:0, totalExp:0};
        uiCtrl.displayBudget(budget);
    }
};