Javascript最佳實踐-應用Module Pattern>盡量減少全局變量
在基于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

浙公網安備 33010602011771號