如何基于DRY原则将重复的事件监听代码重构为可复用函数?
Refactoring to a Reusable Function (DRY Principle)
Great call wanting to follow the DRY (Don’t Repeat Yourself) principle here—duplicate code is always a pain to maintain later. We can easily extract the common logic from both event listeners into a single, reusable function that takes a "step" parameter (either +1 for right, -1 for left) to handle the direction of the slide change.
Here’s how you can refactor your code:
First, create a function that handles updating the activeSlide value with wrap-around logic:
function updateActiveSlide(step) { // Update the active slide index by the given step activeSlide += step; const totalSlides = slides.length; // Handle wrap-around for both upper and lower bounds if (activeSlide >= totalSlides) { activeSlide = 0; } else if (activeSlide < 0) { activeSlide = totalSlides - 1; } // Bonus: If you have code that updates the UI (like showing/hiding slides), // you can move that here too to keep all slide-related logic in one place! }
Then, simplify your event listeners to just call this function with the appropriate step:
rightBtn.addEventListener("click", () => updateActiveSlide(1)); leftBtn.addEventListener("click", () => updateActiveSlide(-1));
Why this works:
- Single source of truth: All the wrap-around logic lives in one place. If you ever need to adjust how the slides loop (e.g., change to a different wrapping behavior), you only modify the
updateActiveSlidefunction once instead of two separate event handlers. - Readability: The event listeners now clearly communicate their intent ("when right button is clicked, move to next slide") without cluttering up the code with low-level index logic.
- Scalability: If you later add more controls (like keyboard arrows or a "jump to first/last slide" button), you can reuse this same function with the appropriate step values.
内容的提问来源于stack exchange,提问作者Amiu
相关产品推荐
相关产品推荐

