2010-05-14 24 views
4

我用半打的jQuery插件,並加上我自己的jQuery的腳本,並在每個腳本我有這樣的代碼:如何組織所有的JQuery腳本

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

什麼是在一個組織中的所有腳本的最佳方式centeralized位置和,而不必多次$(文件)。就緒(腳本函數()無處不在。

想法?

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...... 

我將如何組織上述.js文件?,您會看到上面有多個$(document).ready(function()。

回答

1

你有沒有使用Require.js依賴管理框架考慮?

0

不知道這是否有幫助,但這是我如何組織我的jQuery腳本。我們的應用程序有80K行JavaScript,因此組織非常重要,這對我們很好。

Self Executing Function pattern

+0

我應該指出,你應該向下滾動這個問題到我發佈的答案。 – 2010-05-14 19:41:03

+0

史蒂夫,我已經更新了我的問題,你會怎麼做? – 2010-05-19 02:28:52

2

將所有函數打包到一個對象中,您可以通過將它附加到窗口來鏈接文件。然後傳遞一個匿名函數,在文檔準備就緒的情況下啓動所有依賴於DOM的事件。

例如:

文件1

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

window.MyObj = MyObj 

文件2

var MyObj = window.MyObj; 

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

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

您應該只有一個的document.ready()每個頁面加載執行。否則你做錯了。

希望這會有所幫助。

+0

我已經更新了我的問題,我將如何去組織文件?,..我不清楚你的示例代碼。感謝任何幫助。 – 2010-05-18 20:16:21