4

i am using half dozen jquery plugins and plus my own jquery scripts and in every script i have this code:

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

what is the best way of organizing all the scripts in one centeralized location and instead of having multiple times $(document).ready(function() everywhere in the script.

thoughts?

UPDATE

one.js

$(document).ready(function() {   
$("#aspnetForm").validate({
rules: 
{
<%=txtVisitName.UniqueID %>: 
 {
      maxlength:1, 
       required: true
  },
 deleted lines......

two.js

$(document).ready(function() {
$("#btnSubmit").click(function(event) { 
    if ($("#aspnetForm").valid())
        SaveVisitBasicPage();
     deleted lines......

three.js

$(document).ready(function() {
function initMenu() {
    $('#menu ul').hide();
    $('#menu li a').click(
     deleted lines......

four.js

$(document).ready(function() {

$("#ctl00_cphMaster_txtPurpose").NobleCount('#count01',
{ 
    max_chars: 25,
    on_negative: 'go_red',
    on_positive: 'go_green',
    block_negative: true                     
    deleted lines......

how would i organize the above .js files?, you see above having mulitple times $(document).ready(function().

Nick Kahn
  • 19,652
  • 91
  • 275
  • 406

3 Answers3

2

Pack all of your functions into an object, which you can chain between files by attaching it to window. Then pass an anonymous function that kicks off all of your DOM-dependent events in a doc ready.

example:

file1

var MyObj = {
     init: function(){
     // do stuff
     },
     otherStuff: function(){
     // do other stuff
     }
}

window.MyObj = MyObj

file2

var MyObj = window.MyObj;

MyObj.moreStuff = function(){
     //do more stuff
}

$(document).ready(function(){
     MyObj.init();
     MyObj.moreStuff();
})

You should only have one document.ready() executing per pageload. Or else you're doing it wrong.

Hope this helps.

wookiehangover
  • 430
  • 2
  • 6
  • i have updated my question, how would i go organizing files?,.. i am not clear with your sample code. appreciate any help. – Nick Kahn May 18 '10 at 20:16
1

Have you considered using the Require.js dependency management framework?

Chuck Conway
  • 16,287
  • 11
  • 58
  • 101
0

Not sure if this would help, but this is how I organize my jQuery scripts. Our application has 80K lines of JavaScript, so organization is important, and this has worked for us nicely.

Self Executing Function pattern

Community
  • 1
  • 1
steve_c
  • 6,235
  • 4
  • 32
  • 42