The task is to fetch some data from pokemon api and append it to the list. Api request results have links on previous and next pages.
HTML:
<ul class="poke-list"></ul>
<div class="pagination">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
here's a function that makes an api call (async await is necessary):
var getData = async function (url, pokemonName) {
var response;
if(!pokemonName) {
response = await $.get(url);
} else {
response = await $.get(url + pokemonName);
}
return response;
};
A function to append content and handle click events:
var appendContent = function (data) {
var list = $('.poke-list');
list.empty();
var res = data;
var pokemons = res.results;
pokemons.forEach(function (item) {
list.append($(`<li>${item.name}</li>`));
$('.prev').on('click', function (event) {
res = data;
var url2 = res.previous;
if (url2 === undefined || url2 === null) {
alert('Limit reached!');
} else {
getData(url2)
.then(appendContent);
}
});
$('.next').on('click', function (event) {
res = data;
var url = res.next;
if (url === undefined || url ===null) {
alert('Limit reached!');
} else {
getData(url)
.then(appendContent)
});
});
I call it on page load (yes it is necessary):
$(function {
getData()
.then(appendcontent)
here is a fiddle: https://jsfiddle.net/aikast/4rgcvd7z/
What happens is that every time append function is called it creates new click events (I know that's how it should work), and the code stops working properly (it does not see current ajax call results, so every value is null).
Stopping event propagation did not help.
Is there a way to organise it differently? I can't find a way for click event handlers to see ajax call results outside of appendContent function scope
The question was marked duplicate, but buttons are static, they are not dynamically added!