Home > Mobile >  TypeScript each() as an Arrow function
TypeScript each() as an Arrow function

Time:07-14

I have the following TypeScript function:

$.each($("[data-static-map-image]"), function () {
    $(this).attr("src", $(this).data("mapImageUrl"));
});

I would like to convert this into an Arrow function. Unfortunately, I can't figure out how to make it work with the each loop. Can someone give me a hint?

P.S. I ask for your indulgence as I am still in the beginning of the learning phase.

CodePudding user response:

You can do this in plain JavaScript (and TypeScript too)

Use querySelectorAll to get all elements matching your selector and then use the Array#forEach function:

const allElements = Array.from(document.querySelectorAll('[data-static-map-image]'))

allElements.forEach(element => {
  const url = element.getAttribute('data-mapImageUrl')
  element.setAttribute('src', url)
})

The main reason you cannot use an arrow function in your context is because this refers to the outer scope as opposed when using anonymous functions which have their own this which jQuery is going to bind to each of the elements

CodePudding user response:

The jQuery documentation on jQuery.each explains that the callback gets arguments:

callback
Type: Function( Integer indexInArray, Object value )
The function that will be executed on every value.

So if you really want to stick with jQuery, then make use of the arguments passed to the callback function:

$.each($("[data-static-map-image]"), (i, elem) => {
    $(elem).attr("src", $(elem).data("mapImageUrl"));
});
  • Related