这是去年我在一次公司内部讨论会上的交流主题,相关ppt和样例代码在这里下载

YUI是Yahoo的前端开发框架,它的优点是代码清晰(尽管代码量不小),面向对象和组件,便于协同开发。另外,Yahoo对web开发社区的贡献一直都很积极。

在YUI上扩展开发,一般会采用两种方式,基于对象(object)和基于原型(prototype)。

1. 基于对象(object) 形如Singleton单件模式,保证命名空间整洁,方便管理代码。

HN.app.Book =  {
    dialog:new HN.widget.Dialog(),
    getDialog:function(){
        return this.dialog; 
    },
    paging:function(){......}
}

实例

/**
 * @fileOverview 书架(book) app
 */

HN.namespace('app.Book');

HN.app.Book = (function(){
//YAHOO alias section
var $C = YAHOO.util.Connect,
    $D = YAHOO.util.Dom,
    $E = YAHOO.util.Event,
    $CE = YAHOO.util.CustomEvent,
    dialogId = 'abc';//private variable

    function getBook(id){...}//private method

    return {
        dialog:null,
        getDialog:function(){
            var dg = this.dialog;
            if(!dg) {
                dg = new HN.widget.Dialog({id: dialogId});
                this.dialog = dg;
            }
            return dg;
        },
        getComment:function(bookId,callback){
            var dg = this.getDialog(),
                bookItem = getBook(bookId);
        }
    }//return ends here
})();

2. 基于原型(prototype) 灵活度高,适合编写通用组件。

HN.widget.Dialog = function(config){
    if(config && config.id) 
          this.id = config.id;
}
HN.widget.Dialog.prototype = {
    setBody:function(html){…},
    show:function(){…}
}

实例

/**
 * @fileOverview 评星级(Rating) widget 
 */

HN.namespace('widget.Rating');

(function(){
    //YAHOO alias section
    var $C = YAHOO.util.Connect,
        $D = YAHOO.util.Dom,
        $E = YAHOO.util.Event,
        $CE = YAHOO.util.CustomEvent,
        counter = 0;//private variable
    function find(key,arr){...} //private method

    HN.widget.Rating = function(el,config) {
        this.isInProgress = false;
        this.setConfig(config);
        this.onComplete = new $CE('onComplete', this);
        this.init();
    }
    HN.widget.Rating.prototype = {
        setConfig:function(config){
            if(!config) return;
            for(var attr in config){
                this.config[attr] = config[attr];
            }
        },
        setState:function(){...},
        post:function(id){...},
        init:function(){...}
    }//prototype ends here
})();