如何从JS动画控制代码中移除命名空间作用域下的currentPlayButton变量
完全可以实现。你的场景中currentPlayButton的作用仅为在点击事件和动画结束回调之间传递触发操作的按钮对象,我们可以将该对象临时挂载到DOM节点上,无需保留闭包作用域下的局部变量。
修改步骤:
- 删除闭包内
let currentPlayButton = {};这行变量声明 - 修改
coverClickHandler函数,将点击的按钮临时挂载到body对象上:
function coverClickHandler(evt) { body._currentPlayButton = evt.currentTarget; body.classList.add("initial-fade"); }
- 修改
animationEndHandler函数,从body对象上取到按钮后调用showCover,用完清理临时属性避免残留:
function animationEndHandler(evt) { const animationName = evt.animationName; if (animationName === "initial-fade") { body.classList.remove("initial-fade"); showCover(body._currentPlayButton); delete body._currentPlayButton; } }
修改后完整代码:
const manageCover = (function makeManageCover() { const config = {}; const body = document.body; function show(el) { el.classList.remove("hide"); } function hide(el) { el.classList.add("hide"); } function hideAll(elements) { elements.forEach(hide); } function resetBackground(backgroundSelector) { const allBackgrounds = document.querySelectorAll(backgroundSelector); function hideBackground(background) { background.classList.add("bg1"); } allBackgrounds.forEach(hideBackground); } function resetButtons(buttonSelector) { const allButtons = document.querySelectorAll(buttonSelector); function hideButton(button) { button.classList.add("isOpen"); } allButtons.forEach(hideButton); } function resetPage() { resetBackground("body"); resetButtons(".outer"); } function markAsPlayed(played) { played.classList.add("played"); } function showCover(playButton) { hideAll(config.containers); resetPage(); markAsPlayed(playButton); const cover = playButton.parentElement; cover.classList.add("active"); show(cover); } function animationEndHandler(evt) { const animationName = evt.animationName; if (animationName === "initial-fade") { body.classList.remove("initial-fade"); showCover(body._currentPlayButton); delete body._currentPlayButton; } } function coverClickHandler(evt) { body._currentPlayButton = evt.currentTarget; body.classList.add("initial-fade"); } function addClickToButtons(playButtons) { playButtons.forEach(function playButtonHandler(playButton) { playButton.addEventListener("click", coverClickHandler); }); } function addCoverHandler(coverSelector, handler) { const cover = document.querySelector(coverSelector); cover.addEventListener("click", handler); } function init(selectors) { config.containers = document.querySelectorAll(selectors.container); const playButtons = document.querySelectorAll(selectors.playButton); addClickToButtons(playButtons); body.addEventListener("animationend", animationEndHandler); } return { addCoverHandler, init }; }());
如果希望实现更规范的属性管理,避免直接在DOM对象上挂载自定义属性,也可以使用WeakMap来存储按钮引用,修改逻辑和上述方案一致,仅需把存储载体替换为WeakMap即可。
内容的提问来源于stack exchange,提问作者user17382064
相关产品推荐
相关产品推荐

