0

I have this main function which takes 1 string and 2 callback functions as the argument. Below is the code.

function confirmYesNo(confirmMessage, confirmCallback, cancelCallback) {
    $("#yes-button").click(function () {
         confirmCallback(); //How do I pass confirmCallback arguments
    });
    ...
}

Here is how the function is invoked

function confirmYesNoTest() {
    var confirmContent = "Some Message"
    var id = "1";
    confirmYesNo(confirmContent,
        function (id) { alert(id); }, //alerts undefined
        function () { alert("Cancel Clicked"); });
}

The problem is that the id variable above (which is set to 1) comes out as "undefined" when the confirmCallback executes. Seems something related to scope, but I am not able to get this working.

1 Answer 1

1

The callback should not take any arguments. You could capture the id in a closure:

function confirmYesNoTest() {
    var confirmContent = "Some Message"
    var id = "1";
    confirmYesNo(
        confirmContent,
        function () { alert(id); },
        function () { alert("Cancel Clicked"); }
    );
}

Alternatively, if you didn't want to use closures you could pass the id as parameter to the callback:

function confirmYesNo(confirmMessage, id, confirmCallback, cancelCallback) {
    $("#yes-button").click(function () {
         confirmCallback(id);
    });
    ...
}

and when invoking:

function confirmYesNoTest() {
    var confirmContent = "Some Message"
    var id = "1";
    confirmYesNo(
        confirmContent,
        id,
        function (id) { alert(id); },
        function () { alert("Cancel Clicked"); }
    );
}

Now you can use the callbacks as named functions:

var confirmCallback = function(id) {
    alert(id);
};

and then:

function confirmYesNoTest() {
    var confirmContent = "Some Message"
    var id = "1";
    confirmYesNo(
        confirmContent,
        id,
        confirmCallback,
        function () { alert("Cancel Clicked"); }
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your first approach suits well, particularly when I don't know the exact number of parameters that will be required for the callback. I will be able to capture multiple parameters in closure as mentioned above without worrying about how many of these are there.

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.