更新食谱份数
- 首先我们从控制器开始,创建一个更新份数的方法;
const controlServings = function () {
//更新菜谱份数(在状态上)
model.updateServings(6);
};
- 在控制器中我们不涉及关于数量的方法,这个更新菜谱的方法我们在model中实现
export const updateServings = function (newServings) {
state.recipe.ingredients.forEach(ing => {
//新数量 = 旧数量 * 新的份数 / 旧的份数
// 2 * 8 / 4 * 4
ing.quantity = (ing.quantity * newServings) / state.recipe.servings;
});
state.recipe.servings = newServings;
};
- 之后我们简单的讲更新之后进行渲染一下
//更新菜谱份数
const controlServings = function () {
//更新菜谱份数(在状态上)
model.updateServings(8);
//更新菜谱视图
recipeView.render(model.state.recipe);
};
之后我们来测试一下,当我们的份数减半的时候,份量会不会减半
//加载食谱
const controlRecipes = async function () {
try {
const id = window.location.hash.slice(1);
if (!id) return;
recipeView.renderSpinner();
//(1)加载菜谱
await model.loadRecipe(id);
//(2)渲染菜谱
recipeView.render(model.state.recipe);
//TEST
controlServings();
} catch (err) {
recipeView.renderError();
}
};
将份量手动修改成4时
没问题,当我们将份量手动改为一般的时候,下面的食材的数量也相应的改变;
- 功能测试正常的话,下一步就要开始创建点击事件的方法了
addHandlerUpdateServings(handler) {
this._parentElement.addEventListener('click', function (e) {
const btn = e.target.closest('.btn--tiny');
if (!btn) return;
console.log(btn);
handler();
});
}
- 在init调用即可
const init = function () {
recipeView.addHandlerRender(controlRecipes);
recipeView.addHandlerUpdateServings(controlServings);
searchView.addHandlerSearch(controlSearchResults);
paginationView.addHandlerClick(controlPagination);
};
- 接下俩我们就需要来点击减号或者加号动态的增加或者减少份量了
const controlServings = function (newServings) {
//更新菜谱份数(在状态上)
model.updateServings(newServings);
//更新菜谱视图
recipeView.render(model.state.recipe);
};
- 和分页的操作一样,我们增加增加和减少的类
<div class="recipe__info-buttons">
<button class="btn--tiny btn--increase-servings data-update-to="${
this._data.servings - 1
}">
<svg>
<use href="${icons}#icon-minus-circle"></use>
</svg>
</button>
<button class="btn--tiny btn--increase-servings data-update-to="${
this._data.servings + 1
}"">
<svg>
<use href="${icons}#icon-plus-circle"></use>
</svg>
</button>
</div>
addHandlerUpdateServings(handler) {
this._parentElement.addEventListener('click', function (e) {
const btn = e.target.closest('.btn--increase-servings');
if (!btn) return;
console.log(btn);
const updateTo = +btn.dataset.updateTo;
handler(updateTo);
});
}
- 现在应该没问题了,我们测试一下
这里我们还会发现一些问题,就是更新DOM的时候现在是全部更新,但是有时候我们不需要全部更新,比如增加份数,我们只需要更新部分的DOM就好,后面的文章我们来解决这样的问题