javascript - 如何解决 JavaScript 中 updateServing 函数不工作的问题?

标签 javascript jquery npm

我正在尝试实现一个函数来计算我网站上的成分的份量。

该函数在 Recipe.js 文件中,看起来像这样:

    updateServings(type) {
        // Servings
        const newServings = type === 'dec' ? this.servings - 1 : this.servings + 1;

        // Ingredients
        this.ingredients.forEach((ingr) => {
        ingr.count = this.capDecimal(ingr.count * (newServings / this.servings));
        });
        this.servings = newServings;
       }

问题是当我 console.log(state.recipe);在 index.js 中,此事件监听器起作用,它会在单击网站上的 - 或 + 按钮后控制台记录 state.recipe,但它不会更改配方对象中的服务量:

elements.recipe.addEventListener('click', e => {
    if(e.target.matches('.btn-decrease .btn-decrease *')){
        //Decrease button is clicked
        if(state.recipe.servings > 1){
            state.recipe.updateServings('dec'); 
        } 
    }else if(e.target.matches('.btn-increase .btn-increase *')){
        //Increase button was clicked
        state.recipe.updateServings('inc'); 

    }
    console.log(state.recipe);
});

我点击了 2 次,但属性服务仍然显示 4,如下所示:

https://forum.toshitimes.com/uploads/toshitimes/original/2X/6/6bada9081879db1a14df9bad010382606fda253f.png

这是一个更大的项目,所以我相信我需要包括来自 github 的整个存储库:https://github.com/damianjnc/forkifyApp.git

我需要更改什么才能使其正常工作?

最佳答案

点击事件后需要更新 View

elements.recipe.addEventListener('click', e => {
//....
 try {
    recipeView.clearRecipe();
    recipeView.renderRecipe(state.recipe);
  } catch (error) {
      alert('error processing the recipe:(');
  }

});

注意:你需要声明你的类属性

export default class Recipe {
    ingredients;
    servings;
    constructor(id) {
        this.id = id;
    }

你需要 map 而不是 forEach

this.ingredients = this.ingredients.map((ingr) => {
        ingr.count = this.capDecimal(ingr.count * (newServings / this.servings));
        return ingr;
});

关于javascript - 如何解决 JavaScript 中 updateServing 函数不工作的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54456836/

相关文章:

javascript - 单击后禁用 HTML 链接

javascript - 如何使用jquery更改按钮单击时聚焦的内容可编辑元素的类?

reactjs - 通过 npm 安装 firebase 时遇到错误 |解析附近时 JSON 输入意外结束

node.js - 不能使用 var HtmlReporter = require ('protractor-html-screenshot-reporter' )

javascript - ES6 中定义函数的正确方法?

javascript - .addClass().removeClass() 的问题

javascript - 如何在 Angularjs 中重构闭包中的重复代码?

php - HTML5 : AJAX file upload with progress bar

node.js - Nodejs npm 步骤在 TeamCity 的每个构建中下载包

javascript - 如何在谷歌图表中同时显示水平和垂直网格线