1

How can I get the value of the quantity local variable for the valueChanged method of functionName1 into functionName2 and assign it to a local variable within that?

var functionName1 = function() {
    $newCheckoutNumberPicker.WanSpinner({
        maxValue: 99,
        minValue: 0,
        valueChanged: function(ele, val) {
            var quantity = val              
        }
    });    
}

var functionName2 = function() {
    var test1 = "";
    functionName1();
}
3
  • 1
    Call functionName2() from within the valueChanged function, passing val as a parameter Commented Nov 9, 2016 at 14:51
  • Check javascript closues.. You will get fair Idea of how this works.. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures Commented Nov 9, 2016 at 14:54
  • @Roger can you confirm you need to know the value at time of valueChanged, or just the value itself, which, assuming you're using wan-spinner, you can get with $newChecjoutNumberPicker.val() (ie is this an XY Problem?) Commented Nov 9, 2016 at 15:13

3 Answers 3

4

You can use callback function:

var functionName1 = function(callback) {
    $newCheckoutNumberPicker.WanSpinner({
        maxValue: 99,
        minValue: 0,
        valueChanged: function(ele, val) {
            callback(val)       
        }
    });    
}

var functionName2 = function() {
    var test1 = "";
    functionName1(function (quantity) {
        // ...
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0
valueChanged: function(ele, val) {
    myFunc(val);
 }

And then use the val variable when the value is changer in your fonction.

Comments

0

Make it global in a higher scope.

$(function(){
    var quantity;

    var functionName1 = function() {
        $newCheckoutNumberPicker.WanSpinner({
            maxValue: 99,
            minValue: 0,
            valueChanged: function(ele, val) {
                quantity = val              
            }
        });
    }

    var functionName2 = function() {
        alert(quantity);
    }
});

10 Comments

Global variables are bad, mmmkay.
@Iwrestledabearonce. at least you updated unlike some of the other "answers" :)
If valueChanged is an async method which i assume it is for the need of the callback then this is rather brittle. If you call functionName2 before valueChanged calls-back you will get the wrong value. Which means you need to know when valueChanged has been called, which means you may as well pass a callback in or wrap in a promise.
"My" example? Not me
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.