Search code examples
javascriptjqueryparameters

Call to JavaScript function stop working when adding parameter, is this really not allowed?


When I remove my anonymous function, and call a function directly it only works if it's without the parameter.

Works. With parameter, inside an anonymous function:

$(document).ready(function () {
    $('#someId').on('click', function () {
        setAllOn(checkOn)
    });
});
function setAllOn(checkOn) {
    $("#someId2 input[name='someName']").attr('checked', checkOn);
}

Works. Without an anonymous function, but only without parameters:

$(document).ready(function () {
    $('#someId').on('click', setAllOn);
});
function setAllOn() {
    $("#someId2 input[name='someName']").attr('checked', true);
}

Don't work. A parameter is added, and now it doesn't work:

$(document).ready(function () {
    $('#someId').on('click', setAllOn(true));
});
function setAllOn(checkOn) {
    $("#someId2 input[name='someName']").attr('checked', checkOn);
}

Solution

  • You need to pass a callback to on i.e. a function to be called when the event is fired.

    setAllOn is a function. That's why it works.

    function () { setAllOn(checkOn) } still a function.

    setAllOn(true) is the result of calling function setAllOn. Since it returns nothing the result is undefined. Which is not a function.

    If you want to re-use setAllOn function. You can define a higher order function, taking argument and returning a "curried" version of setAllOn.

    function setAll(checkOn){
        return function(){ return setAllOn(checkOn);}
    }
    
    function setAllOn(checkOn) {
        $("#someId2 input[name='someName']").attr('checked', checkOn);
    }
    
    $(document).ready(function () {
        $('#someId').on('click', setAll(true));
    });