So i'm using the soundcloud API to grab favorites from users. Their max limit is 200 per request, however in the end of the object they have an a_href key who's value is the next page of favorites.
Basically, i'm trying to place a button so that a user can click it and it will feed them the next 200 likes. My issue is getting access to the data.a_href without doing multiple calls to the original API URL. My code looks something like this:
function getAPIURL(username, subSection){
apiurl = "https://api.soundcloud.com/users/" + username + "/" + subSection + "/?client_id=" + clientID + limit + "&linked_partitioning=1"
}
function getFavorites(){
titleList.length = 0;
artistList.length = 0;
imgList.length = 0;
idList.length = 0;
$(".trackList").html("");
username = $("input").val();
subSection = "favorites";
getAPIURL(username, subSection);
getAPI(apiurl);
}
function getAPI(apiurl){
$.getJSON(apiurl, function(data) {
//Does some stuff then
$(".nextPage").on("click", function(){
titleList.length = 0;
artistList.length = 0;
imgList.length = 0;
idList.length = 0;
$(".trackList").empty();
getAPI(data.next_href);
})
});
}
The above works great when I go to the second page. However, when I try to go to the third it's like its calling both the second page and the first page as well before calling the third page....
Any ideas?
This is reapplying the click with every call:
function getAPI(apiurl){
$.getJSON(apiurl, function(data) {
//Does some stuff then
$(".nextPage").on("click", function(){
titleList.length = 0;
artistList.length = 0;
imgList.length = 0;
idList.length = 0;
$(".trackList").empty();
getAPI(data.next_href);
})
});
}
Each time it's called, the number of click handlers goes up by 1 and each will be called.
To stop reapplying it, remove it then apply it. off()
does the removal.
function getAPI(apiurl){
$.getJSON(apiurl, function(data) {
//Does some stuff then
$(".nextPage").off("click").on("click", function(){
titleList.length = 0;
artistList.length = 0;
imgList.length = 0;
idList.length = 0;
$(".trackList").empty();
getAPI(data.next_href);
})
});
}
To make life easier in the future, separate your onclick
binding from the getAPI
call.
If the button isn't present in the DOM until some event happens, bind to a parent element and they'll be no need for off
/on
:
$("PARENT OF THE .nextPage BUTTON").on("click", ".nextPage", function(){
...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With