You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于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 updateActiveSlide function 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:17:33