The function "remembers" the meaning of the problem
This is a simplified partial version of my code to demonstrate the problem:
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 only ONCE click event for this element, but use an external variable that changes from location somewhere else. The point is that this always warns randomNum with an initial value of it when the pairing first happened!
why doesn't it "read" the variable every time the click is fired?
source to share
It might have something to do with insude functions. When you do:
function checkNumber() {
alert(randomNumber);
}
I think this is the same as doing:
myFunc = function checkNumber() {
alert(randomNumber);
}
And therefore it is established as if it randomNumber
were final
. If you need to use randomNumber, you must either take it out of this scope, make it global, or better pass it through functions as a parameter:
function checkNumber(myNumber) {
alert(myNumber);
}
source to share
Why don't you overlay randomNumber on the custom attribute of the element you are adding clickevent to?
function testFunc(){
var randomNum = Math.floor( Math.random() * 100 );
$("#someElement").attr("randomNum", randomNum);
if( !flag ){
addEvents();
flag = true;
};
function checkNumber(){
alert($("#someElement").attr("randomNum"))
}
function addEvents(){
$("#someElement").click(function(e){ checkNumber() });
}
}
This way it always stays with the element, but can be called from all over the place. Pretty messy, but it should work.
source to share