views:

5872

answers:

3

Hello everyone,

I haven't found a good reference for declaring my own functions inside the jquery.ready(function(){});

I want to declare them so they are inside the same scope of the ready closure. I don't want to clutter the global js namespace so I don't want them declared outside of the ready closure because they will be specific to just the code inside.

So how does one declare such a function...and I'm not referring to a custom jquery extension method/function...just a regular 'ol function that does something trivial say like: function multiple( a, b ){ return a * b; }

I want to follow the jquery recommendation and function declaration syntax. I can get it to work by just declaring a function like the multiply one above...but it doesn't look correct to me for some reason so I guess I just need some guidance.

+2  A: 

It might sound simple but you just ... declare the function. Javascript allows functions to have inner functions.

$(document).ready( function() {
   alert("hello! document is ready!");

   function multiply(a, b) {
       return a * b;
   }

   alert("3 times 5 is " + multiply(3, 5));
});
matt b
+7  A: 

I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:

jQuery.ready(function() {

     var myFunc = function() {

           // do some stuff here

     };

     myFunc();


});
jonstjohn
Bingo, this is what i was looking for because it's more clear about the scope of the function and follows the jquery syntax better it seams. Thank you for this answer.
Ralph
Sorry if it's a stupid comment but this answer confuses me.Shouldn't the function call rather be "myFunc();" instead of "myFunction();" ?
Benjamin Delichère
+1  A: 

I have a StartUp function, and I use it as printed bellow:

function StartUp(runnable)
{
    $(document).ready(runnable.run);
}

var ExternalLinks =
{
    run: function()
    {
     $('a[rel="external"]').bind('click', ExternalLinks.click);
    },
    click: function(event)
    {
     open(this.href);
     return false;
    }
}
StartUp(ExternalLinks);

var ConfirmLinks =
{
    run: function()
    {
     $('a.confirm').bind('click', ConfirmLinks.click);
    },
    click: function(event)
    {
     if (!confirm(this.title)) {
      return false;
     }
    }
}
StartUp(ConfirmLinks);

My web sites are modular, so every module has N actions and every action can have a .js file, so I just write function and call it with StartUp(...functionName...)

glavić