jquery onSubmit,onComplete等

时间:2011-07-08 01:47:43

标签: javascript jquery ajax

我注意到jQuery中构建的很多工具,尤其是那些使用某种ajax的工具,都有onSubmit,onComplete等钩子。

这种做法是否有名称及其特征?

这种做法的文化是jQuery社区的一部分,还是一个更大的javascript现象?

您是否可以推荐使用此方法构建工具的指南?

1 个答案:

答案 0 :(得分:2)

是的,它被称为观察者设计模式。它并不孤立于JQuery甚至是JavaScript。许多设计模式可以在大多数编程语言中实现。

DevShop是javascript设计模式的框架。他们的Observer模式如下所示:

<强>观测

(function(){
    DevShop.Me({
        Observer:function(obj){
            var observer=function(){
                this.onRegister=function(){};
                this.notify=function(eventName,observable){
                    this.observable=observable;
                    if(typeof this[eventName]==="function")
                        try{this[eventName]();}catch(e){}
                };
            };
            return DevShop.SingletonFactory({extend:observer,instance:obj});
        }
    });
})();

<强>可观测

(function(){
    DevShop.Me({
        Observable:function(obj){
            var observable=function(){
                this.observers=[];
                this.addObserver=function(o){
                    if(typeof o==="function"||typeof o==="object"){
                        if(typeof o.notify==="function"){
                            this.observers.push(o);
                            if(typeof o.onRegister==="function")
                                try{o.onRegister();}catch(e){}
                        }
                    }
                };
                this.notifyObservers=function(eventName){
                    var size=this.observers.length;
                    for(var x=0;x<size;x++){
                        try{
                            this.observers[x].notify(eventName,this);
                        }catch(e){}
                    }
                };
            };
            return DevShop.SingletonFactory({extend:observable,instance:obj});
        }
    });
})();

您可以在此处详细了解观察者设计模式:http://en.wikipedia.org/wiki/Observer_pattern