如何解决JavaScript无法运行updateServing函数的问题?

时间:2019-01-31 09:01:57

标签: 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中,此事件侦听器起作用,它将在单击网站上的-或+按钮后控制台记录日志状态。但是不会更改配方对象中的投放量:

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

要使其正常运行,我需要更改什么?

1 个答案:

答案 0 :(得分:1)

点击事件后,您需要更新视图

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

并且您需要地图而不是forEach

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