Thursday, 9 June 2016

jquery - Javascript closures and scope issues




I can't wrap my head around javascript closures. I want 4 random numbers, but only get the the last one replicated 4 times.




Javascript



$(function() {      

function setNewNumber(element) {
return function (newNumber) {
element.text(newNumber);
}
}


$('.number').each(function() {
$.get('http://www.random.org/integers/?num=1&min=1&max=6&col=1&base=10&format=plain&rnd=new',
setNewNumber($(this))
);
});

});



HTML









A working plunker example




Any hints?


Answer



The get request is being cached.



http://jsfiddle.net/hCEbd/1/



(That is to say your understanding of closures is correct and the code is working correctly).



From comments, because this is relevant:





You can request multiple numbers from random.org at the same timer per their API. Instead of using four requests, use num=' + $(".number").length and then do a little parsing



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...