6

Questions about how to organize jQuery functions in a single function

 3 years ago
source link: https://www.codesd.com/item/questions-about-how-to-organize-jquery-functions-in-a-single-function.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Questions about how to organize jQuery functions in a single function

advertisements

I've noticed sometimes people put a bunch of callable functions within their $(function() { ...here... }); block. I wondered why but then noticed a possible reason: naming collisions don't appear to be a concern if the two objects are in different jQuery code blocks.

Is my thinking correct? This would seem to be a big advantage.

But now that I've taken this approach, I have the need to make one of my functions callable from other jQuery code blocks. So I can move the function outside the code block, but it needs to call other functions inside the code block.

So do I need to move all my functions outside the code block, or is there a way to keep this separation but still be able to call one of my functions from another code block?


The fact that they are using jQuery's document.ready shortcut is not really as much of an issue for defining the variables, as much as the fact that the variables (or functions) are inside of a closure created by the anonymous function

`function(){}`

So yes, this is primarily done to avoid polluting the global namespace. It is also done with the hopes that once out of scope, the garbage collector may be able to collect some of what was in there (since it is out of scope).

If you want to have a global variable, there is nothing wrong with that, just try to limit them as much as possible. If you need one from inside of the ready block, then just define it outside and reference that inside.

var MyGlobalObj_guid52z = {};
$(function(){
 MyGlobalObj_guid52z.MyFunction = function(){
  //do what you want in here
 };
});
//and later you can do this
MyGlobalObj_guid52z.MyFunction();


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK