Scoping Functions in Document Ready
When writing your event handlers in your document ready, it sometimes happens that you have the same functionality bound in a few different places. It is really easy to make a function that is not visible outside of your document ready but that allows you to reuse that code.
Let's say, for example, that you have a link's click event and input field's keypress event that both need do the same simple action. We definitely want to reuse the same code for both places, but don't want the function exposed to the whole world. The easy thing to do is just declare the function in the bottom of your document ready's anonymous function, like so:
[js]
$(function() {
$("a").click(doSomething);
$(":text").keypress(doSomething);
function doSomething() {
console.log("we did something!");
};
});
[/js]
This way, we have a local function that is accessible only from inside the document ready block. Reducing the scope like that will prevent accidental usage in other places, but still keep the code clean.