Search code examples
javascriptarraysmutation-observers

Throwing Callback functions with different names


I'm newbie in coding and this is my first question, so I'll try to explain very clear.

I have an image slider and I'm trying to change text in every slide. I have Mutation Observer in JavaScript which is watching classlist for class changing, so when a div have "active" class, I'm throwing a callback function.

A carousel have lot of image sliders inside;

carousel.forEach(e=>{
    let i= 1;
    let workOnClassAdd=`workOnClassAdd${i}`
    new ClassWatcher(e, 'active',workOnClassAdd,workOnClassRemoval)
    i++;
})

function workOnClassAdd1(){};
function workOnClassAdd2(){};
.
.

So in this code, I'm trying to create watchers with different functions but workOnClassAdd is looking like a string, so I got "this is not a func" error. How can i throw different variables in this forEach method?

Thanks anyway, good coding :)


Solution

  • You can write functions that return functions. Something like:

    function getCallbacksFor(iValue) {
      return [
        function workOnAdd() {
          console.log('add class work for', iValue);
        },
        function workOnRemove() {
          console.log('remove class work for', iValue);
        },
      ];
    }
    
    carousel.forEach((e, idx) => {
      new ClassWatcher(e, 'active', ...getCallbacksFor(idx))
    })