简体   繁体   中英

How to access function from outside an extended function?

I have this code

(function ($) {
    $.fn.Val_Rev2 = function (containerId) {
        let container = document.getElementById(containerId);
        let allFields = container.querySelectorAll("[is-required]");
        let errorList = [];

        // A bunch of other code....
        
        function PrintErrorSummary() {
            // Do stuff
        }
    }
}(jQuery));

and I can access the Val_Rev2 by doing

$(this).Val_Rev2("container");

I don't know how to access PrintErrorSummary() and I need to on a button click event so I can see errorList that gets populated from other code in the Val_Rev2

I could just pass in another id for a button and bind an event to that so I can access the errorList, but would like to know of any other ways to access the PrintErrorSummary

I tried...

I'm not sure what Val_Rev2 function would return, but I think PrintErrorSummary function needs the defined variables in Val_Rev2 to print something.

You can do something like this:

(function ($) {
$.fn.Val_Rev2 = function (containerId) {
    let container = document.getElementById(containerId);
    let allFields = container.querySelectorAll("[is-required]");
    let errorList = [];

    // A bunch of other code....
    
    function PrintErrorSummary() {
        // Do stuff
    }

    return {
         PrintErrorSummary: PrintErrorSummary,
         // other stuff if needed
    }
}
}(jQuery));

And you can access the function as shown below:

$(this).Val_Rev2("container").printErrorSummary();

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