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?

+2


source to share


4 answers


You are setting a value for a global variable. Then you will be warned about it when the button is pressed. The value has been set only once and will not change each time the button is pressed.



0


source


is it really global? try the window.randomNum alert



+4


source


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);
}

      

0


source


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.

0


source







All Articles