简体   繁体   中英

How can I make this code into a reuseble function by implementing DRY principle?

I'm trying to apply my code in one simple function with parameters and make it reusable due to the DRY principle. As you can see I use pretty the same code in both of my addEventListener Function . Here is the code that I want to make reusable in my addEventListener function :

 rightBtn.addEventListener("click", () => {
      activeSlide++;
      if (activeSlide > slides.length - 1) {
        activeSlide = 0;
      }
    });

    leftBtn.addEventListener("click", () => {
      activeSlide--;
      if (activeSlide < 0) {
        activeSlide = slides.length - 1;
      }
    });

You can simply create a function that passes in a value by which you increment or decrement the slide index. And then you can update the slide index as shown in the snippet below.

 const slides = ["Apple", "Mango", "Banana"]; let currSlide = 0; const leftBtn = document.querySelector("#leftBtn"); const rightBtn = document.querySelector("#rightBtn"); const content = document.querySelector("#content"); content.innerText = slides[currSlide]; const changeSlide = (delta) => { currSlide = (currSlide + delta + slides.length) % slides.length; content.innerText = slides[currSlide]; }; leftBtn.addEventListener("click", () => changeSlide(-1)); rightBtn.addEventListener("click", () => changeSlide(1));
 <button id="leftBtn">Left</button> <span id="content"></span> <button id="rightBtn">Right</button>

They only look similar but are completely different.

You can do like this:

const changeSlide = diff => () => {
  activeSlide += diff;
  if (activeSlide < 0) {
    activeSlide = slides.length - 1;
  } else if (activeSlide > slides.length - 1) {
    activeSlide = 0;
  }
  return activeSlide;
};
rightBtn.addEventListener("click", changeSlide(1));
leftBtn.addEventListener("click", changeSlide(-1));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM