简体   繁体   中英

javascript strategy / best practice

I'm getting into writing some more complex javascript applications, and I'm running into the limitations of my own knowledge-- please forgive any naming errors or obvious noob stuff, I'm not a js pro!

I have about 4 or 5 scripts I've put in their own files, just to keep things a little easier to maintain. So maybe there's one script that deals with building page elements (like complex forms), another that just handles data, creating generic ajax request objects, defining parsers and error functions for the data returned, and another that is purely display-oriented.

I've set global variables in the page that then get populated by various scripts that get loaded at run time. For example, I define var myapp = { }; in the main HTML page, and then in the scripts various function populate this "namespace" like:

myapp.myfunction = function(){
    // do stuff
}

The problem is that despite all the scripts including a $(document).ready(function() block that wraps all function definitions, when a function is called from one script that refers to another (that is, if my data.js file calls a function myapp.myDisplayFunction that is in the display.js file, I sometimes get an Object has no method 'myDisplayFunction'

Other than slamming all functions into one massive script, how do you deal with this problem? Is there a best practice that I'm missing? or is this just a question of specifying a different order that the scripts are called in?

Thanks

When you are not sure if method you are about to call exists (is already loaded) you can do a check:

if (myapp) //my app namespace is defined
{
    if (myapp.myFunction) //myFunction is defined
    {
        myapp.myFunction();
    }
    else
        alert('You have to load myFile.js first!');    
}

Just check for the function before using:

if(typeof(myapp.myDisplayFunction) !== undefined) {
    // do your stuff
} else {
    // wait for a while
}

And check whether you have async attribute set while loading the .js files.

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