I have some experimental input checking Javascript:
$(function(){
var check_stuff = function(elem){
//...code to check stuff
};
// grab every input element with a checkable class
$('input.checkable').each(function(i) {
$(this).click(function(){
if check_stuff(elem) {
$(this).submit(); // submit if passes checks
}
};
});
});
Which works. However, I’m concerned this is polluting the global space. So if ‘check_stuff’ function is defined somewhere in jQuery or by another module sharing $, I have effectively just overridden it. Is that correct?
If I remove the $ on the first line:
(function(){
Then I believe I am creating a standard javascript anonymous function, which effectively isolates check_stuff. However, the:
$(this).click(function(){
…no longer executes on DOM ready (since it is executed as soon as its evaluated). I’ve tried wrapping it in jQuery(document).ready to no-effect.
Whats the right way of creating a module that executes a block of code on ready?
You can wrap your code in a
self-executing anonymous function. This code will run, and all variables included within this function will only exist within the local scope of that function. The()after the function definition will execute the function immediately.Format:
Place that in the dom ready & you’ll be good to go.
Example: http://jsfiddle.net/VZ2ay/2/