0

It might me due to the insomnia, but I've been having trouble getting the following, simple JS function to work.

function numFunction() {
    var retNum = null;
    $('.draggable').draggable($state).on("drag", function (event, ui) {
        retNum = 31;
    });
    return retNum;
}

var finNum = numFunction();

It is as easy as this:

  • We start of by creating a function with the name numFunction.
  • The variable retNum is defined. The variable changes its value due to an event triggered by jQuery UI draggable (which works perfectly fine).
  • Return retNum
  • Last but not least, define new variable finNum with function's (supposed) new value of 31.
  • End of story.

Unfortunately, it doesn't work. console.log(finNum) only returns null. I am about to bash my head against the wall: I don't know what I am missing.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
sdny
  • 156
  • 1
  • 1
  • 10
  • 1
    This doesn't make a lot of sense. Running he function and returning a value is a time thing. And it happens immediately, at which point the event handler cannot have been triggered yet. And subsequent riggers of the event handler won't magically run the function again. The logic is flawed. What you should instead is trigger the code that needs access to the variable from inside the event handler. Have a look at http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call , which is basically the same situation. – Felix Kling May 13 '14 at 02:18
  • That makes perfect sense. Will do some additional reading. My whole thinking right now is inside out. – sdny May 13 '14 at 02:25

1 Answers1

1

You are only changing the value of the retNum on draggable event handler, which only executes once the event is triggered.

But, it won't happen unless that event has triggered.

When you are calling the function, the handler might not yet be triggered, so the retNum remains null

So do this:

function numFunction() {
    var retNum = null;
    $('.draggable').draggable($state).on("drag", function (event, ui) {
        retNum = 31;
    }).trigger('drag');<- trigger it immediately to set the value of retNum to 13
    return retNum;
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95