简体   繁体   中英

How to rewrite this JS Method without the Arrow Functions?

I need to get rid of the arrow functions for the following methods from animate.style; I need to run this code on a legacy chromium browser (40) that does not support arrow functions. I am trying to morph it into a traditional legacy function, but keep getting syntax errors as my brain seems to only work with arrow functions. Any help with this challenge is deeply appreciated!

const animateCSS = (element, animation, prefix = 'animate__') =>
  // We create a Promise and return it
  new Promise((resolve, reject) => {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });

And this is how we use the above method, which also contains an arrow function:

animateCSS('.my-element', 'bounce');

// or
animateCSS('.my-element', 'bounce').then((message) => {
  // Do something after the animation
});

remove the =>. prepend the function key word before the function block. don't leave any blocks unwrapped.

const animateCSS = function (element, animation, prefix = 'animate__') {
  // We create a Promise and return it
  new Promise(function (resolve, reject) {
    const animationName = `${prefix}${animation}`;
    const node = document.querySelector(element);

    node.classList.add(`${prefix}animated`, animationName);

    // When the animation ends, we clean the classes and resolve the Promise
    function handleAnimationEnd(event) {
      event.stopPropagation();
      node.classList.remove(`${prefix}animated`, animationName);
      resolve('Animation ended');
    }

    node.addEventListener('animationend', handleAnimationEnd, {once: true});
  });
  }
  
  animateCSS('.my-element', 'bounce');

// or
animateCSS('.my-element', 'bounce').then(function (message) {
  // Do something after the animation
});```

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