Ainda com a pokédex do último tópico, eu estou tentando fazer a mesma coisa que eu fiz no evento inline (exemplificado no snippet abaixo), só que com um event listener.
let offset = 0;
const limit = 10;
function loadPokemonItems(offset, limit) {
pokeApi.getPokemons(offset, limit).then((pokemons = []) => {
const pokemonItems = pokemons
.map((pokemon) => {
return `
<a
href="pokemon-profile.html"
onclick="setPokemonProfile(
'${pokemon.number}'
, '${pokemon.name}'
,'${pokemon.image}'
, '${pokemon.types}'
)
"
>
<li class="pokemon ${pokemon.type}">
<span class="number">#${pokemon.number}</span>
<span class="name">${pokemon.name}</span>
<div class="detail">
<ul class="types">
${pokemon.types
.map(
(type) => `
<li class="type ${type}">${type}</li>
`
)
.join("")}
</ul>
<img src="${pokemon.image}" alt="${pokemon.name}" />
</div></li
></a>
`;
})
.join("");
pokemonList.innerHTML += pokemonItems;
});
}
loadPokemonItems(offset, limit);
Mas por algum motivo eu só consigo pegar os dados do primeiro item do array (no caso, o Bulbassauro):
let offset = 0;
const limit = 10;
function loadPokemonItems(offset, limit) {
pokeApi
.getPokemons(offset, limit)
.then((pokemons = []) => {
const pokemonItems = pokemons
.map((pokemon) => {
return `
<a href="pokemon-profile.html">
<li class="pokemon ${pokemon.type}">
<span class="number">#${pokemon.number}</span>
<span class="name">${pokemon.name}</span>
<div class="detail">
<ul class="types">
${pokemon.types
.map(
(type) => `
<li class="type ${type}">${type}</li>
`
)
.join("")}
</ul>
<img src="${pokemon.image}" alt="${pokemon.name}" />
</div></li
></a>
`;
})
.join("");
pokemonList.innerHTML += pokemonItems;
return pokemons;
})
.then((pokemons = []) => {
const links = Array.from(document.getElementsByTagName("a"));
links.forEach((link) =>
link.addEventListener("click", () =>
pokemons.forEach((pokemon) => {
setPokemonProfile(
pokemon.number,
pokemon.name,
pokemon.image,
pokemon.types
)
}
)
)
);
});
}
loadPokemonItems(offset, limit);
Função setPokemonProfile:
const setPokemonProfile = (number, name, image, stringTypes) => {
const iterableTypes = stringTypes.split(",")
const pokemon = { number, name, image, iterableTypes };
sessionStorage.setItem("pokemon", JSON.stringify(pokemon));
};
Alguém consegue me ajudar a atribuir o event listener para todos os itens? https://github.com/kellysondias/pokedex-dio/blob/event-listener/assets/js/index.js