-3

This is the current legacy code

$('#container input[type="number"], #container input[type="text"]').replaceWith(function () {
    return $(`<p class="readonly" id="${$(this).prop('id')}">${$(this).val()}</p>`).append($(this).contents());
});

I need to do some clean-up and refactoring and was hoping to modernize this but replaceWith doesn't seem to have an argument I can use to substitute for 'this' in the places where we're using it like $(this).prop. I thought it should be event.currentTarget but that didn't work (or maybe my implementation was wrong)

Alexander Keefe
  • 23
  • 1
  • 2
  • 3
  • 3
    So, first question. Why? If your logic is written using `this`, and it works, why swap to arrow functions? Arrow functions can accept in the arguments passed to them and use them. I'm just slightly confused why you want to refator it when it already works. – Taplar Jan 17 '20 at 16:15
  • Does this answer your question? [Can you bind 'this' in an arrow function?](https://stackoverflow.com/questions/33308121/can-you-bind-this-in-an-arrow-function) – JBis Jan 17 '20 at 16:41
  • I wanted to refactor it mostly because of style reasons. Our linter setup is flagging it as an "unexpected 'this' – Alexander Keefe Jan 17 '20 at 18:37

2 Answers2

0

replaceWith doesn't seem to have an argument I can use to substitute for 'this'

It doesn't.

The documentation shows that the function is not passed any arguments.

Arrow functions are simply not suitable for use here. There were never designed as a universal replacement for function declarations or expressions.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • https://jsfiddle.net/34fabqwL/ technically the method is given arguments, but neither of them are the element being replaced. – Taplar Jan 17 '20 at 16:23
-2

Can you do this with arrow functions? Yes-ish. The method you give the replaceWith does not provide the element you want to replace, but it does give you the index. So with that in mind, if you just have to use arrow functions for whatever reason, you could use that index to get your element.

const $inputs = $('input');

$inputs.replaceWith( index => {
  let input = $inputs[ index ];
  
  return `<p class="readonly" id="${input.id}">${input.value}</p>`;
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input1" value="Value 1">
<input type="text" id="input2" value="Value 2">
<input type="text" id="input3" value="Value 3">

My personaly opinion, it doesn't make much sense to switch to arrow functions in this case, but it can be done.

Taplar
  • 24,788
  • 4
  • 22
  • 35