简体   繁体   中英

Passing Parameters into a Callback Function

I have a function that listens for a click on the screen and fires a callback. It is part of a Helper object (which is why is preceded by the term Helper in my sample code. That is irrelevant however.

var Helper = { 
    bodyClickListener: function(fn) {
        var window = document.getElementsByTagName('body')[0];
        window.click();
        CORE.dom.on(window, 'click', function(event) {
            CORE.dom.off(window, 'click');
            fn(event);
        });
    }
}

I need to be able to pass a function into this function with a parameter that has been previously set.

function someFunction() {    
    var popup = document.getElementById('tagResultsPopup');
    Helper.bodyClickListener(function(popup) {
        return function(event) {
            event.stopPropagation();
            removePopup(popup);
        };              
    }(document.getElementById('tagResultsPopup')));

    function removePopup(element) {
        if(element) {
            element.parentNode.removeChild(element);
        }
    };
}

The code above works, but you'll notice that I have to set the popup variable inside of the callback function. It has already been set above. How do I pass a reference to the earlier variable into the callback function.

If I understand your question correctly, you don't need to do much. You can just use the popup variable defined outside.

var popup = document.getElementById('tagResultsPopup');
Helper.bodyClickListener(function(event) {
    event.stopPropagation();
    //Don't set it  
    //var popup = document.getElementById('tagResultsPopup');
    removePopup(popup);//popup will refer to the correct variable
});

The function that you are passing to bodyClickListener is a closure. You can simply reference 'popup' inside that function without any problem. You don't have to create a new variable.

The answer was to use closure in this way:

Helper.bodyClickListener(function(popup) {
    return function(event) {
        event.stopPropagation();
        removePopup(popup);
    };              
}(document.getElementById('tagResultsPopup')));

That way the callback function has access to the variable I pass into the parameter function. So here, the return is actually the function I am passing as the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM