This is a simplified partial version of my code to demonstrate the issue:
function testFunc(){
var randomNum = Math.floor( Math.random() * 100 );
if( !flag ){
addEvents();
flag = true;
};
function checkNumber(){
alert(randomNum)
}
function addEvents(){
$("#someElement").click(function(e){ checkNumber() });
}
}
I want to bind the click event only ONCE for this element, but use outside variable that changes from someplace else. thing is, this always alerts randomNum with the initial value it
had when the bind first took place!
why doesn’t it “reads” the variable everytime click is triggered?
You are setting a value to a global variable. Then you are alert’ing the value on the button click.
Value was set only once and will not change on every click of the button.