views:

116

answers:

4

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?

A: 

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.

Paulo Manuel Santos
no it is set again and again all over the code i've mentioned that.
vsync
I think the problem is that he change the value of randomNum later in the script but before the event is triggered, and that this change doesn't appear when the event is finally triggered. But maybe i misunderstand his question, my english is not perfect :-)
p4bl0
its supposed to change before the event is triggered :)
vsync
+3  A: 

is it really a global? try alerting window.randomNum

anonymous
yes, its not global i just realized..i'm such a moron.
vsync
@vsync - sorry, looks like I answered a different question altogether, it's beyond me how I got four upvotes in a few minutes!
karim79
A: 

This might have something to do with functions insude functions. When you do:

function checkNumber() {
    alert(randomNumber);
}

I think is the same as doing:

myFunc = function checkNumber() {
    alert(randomNumber);
}

And is therefore set, as if randomNumber was final. If you need to use randomNumber you should either move it outide that scope and make it global, or better, pass it through the functions as a parameter:

function checkNumber(myNumber) {
    alert(myNumber);
}
jeef3
I thought about passing it, but the checkNumber function only called on Click event, and its the same issue there also, because its only bind once. I thought because "checkNumber" is living inside "testFunc" it could use its variables also.I've moved its to be a Global var, but its damn ugly solution :/
vsync
A: 

Why don't you stick the randomNumber up a custom attribute of the element you're adding the 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() });
    }
}

That way it always stays with the element, but is callable from allover the place. Pretty messy, but it should work.

Powertieke