I'm trying to have a callback call a function inside $(document).ready(..)
How do I call a function from outside this?
Like for example:
$(document).ready( function(foo) {
var bar = function() { ... };
});
// How do I call bar() from here?
I'm trying to have a callback call a function inside $(document).ready(..)
How do I call a function from outside this?
Like for example:
$(document).ready( function(foo) {
var bar = function() { ... };
});
// How do I call bar() from here?
That depends on how you want to scope things. If you just want bar to be in the global scope, then just do this:
$(document).ready( function(foo) {
var bar = function() { ... };
window.bar = bar;
});
Remember, in JavaScript the only code blocks that have scope are functions, so variables declared in if{}
, while{}
, and other types of code blocks are global to whatever function they are a part of, unless they are not declared.
If you use a variable without declaring it, that is the same as doing:
// Both of these variables have global scope, assuming
// 'bar' was never declared anywhere above this
window.foo = "Hello World!";
bar = "Hello World!";
So the example above could be a line shorter by doing:
$(document).ready( function(foo) {
window.bar = function() { ... };
});
You can declare bar outside of your ready function. It will be global then.
var bar;
$(document).ready( function(foo) {
bar = function() { ... };
});
If you want to call bar()
from the outside, why don't you just declare it on the outside, passing it whatever parameters you need from the inner scope?
function bar(baz, qix) { ...};
$(document).ready(function(foo) {
bar(whatever, whatnot);
});
bar(something, else);
Don't declare everything inside of the ready function
$(document).ready( function() {
...
bar();
});
function bar() {
...
}
After reading your comment, maybe you want to do something like this. Use myUtilities
to minimize global namespace pollution if you're going to want to be accessing things inside and outside your ready
.
var myUtilities={};
$(document).ready( function(foo) {
myUtilities.bar = function() { ... };
});
// How do I call bar() from here?
a = myUtilities.bar();
Sorry, untested. Might be a dumb syntax mistake or two in there.