Javascript最佳实践-应用Module Pattern>尽量减少全局变量

在基于Html的应用中,js的全局变量比较邪恶,一来容易与别人的js代码或js框架产生冲突,二来影响页面性能。两年前Levin曾经看到过Douglas Crockfordhttp://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 标签: ,

你可能感兴趣的:(JavaScript)