我正在尝试实现一个函数来计算我网站上的成分的份量。
该函数在 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,如下所示:
这是一个更大的项目,所以我相信我需要包括来自 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/