1

There is some code that another developer repeated. I want to put that in a function and then call it but now I am a bit confuse.

This is the code I have:

if(true) {
    $(this).attr('id', function (i, val) {
       return val.replace('Less', 'More');
    }).attr('data-bactmln', function (i, val) {
       return val.replace('Less', 'More')
    });
} else {
    $(this).attr('id', function (i, val) {
       return val.replace('More', 'Less');
    }).attr('data-bactmln', function (i, val) {
       return val.replace('More', 'Less')
    });
}

And I would like to do something like this:

var toggleTealiumId = function(p1, p2) {
    return val.replace(p1, p2);
};

if(true) {
   $(this).attr('id', toggleTealiumId('More', 'Less'));
} else {
   $(this).attr('data-bactmln', toggleTealiumId('Less', 'More'));
}

That val is the value of the string as in the first lines of code, but for now I am getting undefined.

So how can I stop val from being undefined and do it in a proper way?

Any suggestions?

Non
  • 8,409
  • 20
  • 71
  • 123

1 Answers1

3

You would need to write it that way:

function toggleTealiumId(p1, p2) {
  return function(i, val) {
    return val.replace(p1, p2);
  }
}

The call toggleTealiumId('More', 'Less') will return a function where p1 and p2 are bound to 'More' and 'Less' (Take a look at How do JavaScript closures work? for more details), this function then can be passed as argument to attr.

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • I typically like to name these functions that return handlers something that implies that it returns a function. For example, `createToggleTealiumCallback` – Ruan Mendes Mar 07 '18 at 21:33