在基於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