views:

143

answers:

5

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?
+5  A: 

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() { ... };
});
Dan Herbert
this has the same effect as simply omitting the "var" before "bar"
llimllib
Thanks a lot Dan!
LB
While this would work, how is this different from removing the $(document).ready() entirely and simply declaring this outside: /* $(document).ready( function(foo) { */ window.bar = function() { ... }; /* });*/
jacobangel
A: 

You can declare bar outside of your ready function. It will be global then.

var bar;

$(document).ready( function(foo) {
   bar = function() { ... };
});
Geoff
Isn't it global even without that declaration at the top?
Nosredna
@Nosredna: implicit globals killed my parents
Jimmy
A: 

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);
slipset
+2  A: 

Don't declare everything inside of the ready function

$(document).ready( function() {
  ...
  bar();
});

function bar() {
  ...
}
Chris Brandsma
A: 

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.

Nosredna