Javascript最佳實務-應用Module Pattern>盡量減少全域變數

來源:互聯網
上載者:User

在基於Html的應用中,js的全域變數比較邪惡,一來容易與別人的js代碼或js架構產生衝突,二來影響頁面效能。兩年前Levin曾經看到過Douglas Crockford(http://www.crockford.com/)提到的module pattern of javascript,利用這種代碼模式可以最低限度的減少全域變數汙染dom上下文,後來Yahoo的js架構YUI便採用了這種模式。Levin當然也不例外,並在原先的module pattern上稍加改進,現在Levin的js代碼模板如下,希望大家可以參考下:

---------------------------------------------------------------------------------------------

///<reference path="../jquery/jquery-1.3.2.js"/> ///<reference path="../Vivasky.StringUtils.js"/> ///<reference path="../Vivasky.com.js"/> ///<reference path="Local.Common.js"/> /*-----Note:This file Contains client logic for Page xxxx-----*/ var this$ = function(p,pub) {     //private area     p.initVar = function(opts) { };     p.onLoaded = function() { };     p.initEvents = function(opts) {         $(document).ready(p.onLoaded);     };     //public area     pub.Init = function(opts) {         p.initVar(opts);         p.initEvents(opts);     };     return pub; } ({},{}); 

---------------------------------------------------------------------------------------------

有了這個代碼模板,再配合使用文本擴充工具(Levin用的是Fastfox),每次寫一個頁面的js邏輯時,只需打“appjs”按斷行符號便可以迅速打出上述模板啦!然後再根據不用的頁面在模板上添磚加瓦~

說明:

1,上述模板中的this$純粹是個人命名愛好,別忘了換成你自己喜歡的!

2,p.initVar方法用於聲明私人變數,一般用於引用頁面中需要重複使用的元素

3,p.onLoaded方法用於放頁面載入完畢後的邏輯

4,p.initEvents方法用於為頁面元素進行事件註冊

應用上面模板,一個完整的頁面javascript邏輯如下(Levin首頁的app.default.js):

http://docs.google.com/View?id=dtxft7f_211ng5b26hc

另外,想更詳細瞭解javascript module pattern的同學,請參考以下文章:

http://ajaxian.com/archives/a-javascript-module-pattern

http://yuiblog.com/blog/2007/06/12/module-pattern/

My website's folder structure looks like,

website\                                --website root

website\assets\                      --website's static resources  
website\assets\css\                 --css folder

website\assets\js\                    --main javascript folder.common js files goes here

website\assets\js\jquery\         -- jquery and jquery plugins goes here

website\assets\js\local\           --i put all my client javascript files of the website in the folder named local

website\assets\js\release\        --compressed,combined js files for deploy use 
website\assets\img\                --image folder

Technorati 標籤: jQuery,javascript

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.