简体   繁体   中英

Store variables and functions in document

Im building a webapp where i load the main page with its own javascript file in the index.html then the nav is calling all other pages in a div without a browser refresh using $.ajax and attaching specific script for each page in the div too with $.getScript.

Sometimes i needs to access a method declared in the main page javascript from within the div loaded javascript so what i generally do is attach the main method to document, exemple, instead of just:

let doThis = function(num){
// do your stuff
}

i do this

document.doThis = function(num){
// do your stuff
}

This way i can easily access it from any other javascript file loaded at different levels.

Thing is i feel its not a good practice, what would then be the good practice? or is it acceptable one?

If you are not using any bundler,then ' Revealing Module Pattern ' can be used as a good practice here. This will allow the syntax to be more consistent and in this case, will make it easier to tell which of the functions can be accessed globally.

window.mainPageModule = (function () {

    var privateVar = "abcd",

    function privateFunction() {
        //Do some private stuff here
    }

    function publicSetValue(value) {
        privateVar = value;
    }

    function publicGetValue() {
        return privateVar;
    }


    // Reveal desired functions to public

    return {
        doThis: publicSetValue,
        getThis: publicGetValue
    };

})();

Then, to access the public function anywhere globally

mainPageModule.doThis("1234")

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