开发者

jquery onSubmit, onComplete, etc

开发者 https://www.devze.com 2023-03-18 16:37 出处:网络
I notice that a lot of tools built in jQuery, and particularly those that use some kind of ajax, have hooks such as onSubmit, onComplete, etc.

I notice that a lot of tools built in jQuery, and particularly those that use some kind of ajax, have hooks such as onSubmit, onComplete, etc.

Is there a name for this practice and the conventions that ch开发者_开发问答aracterize it?

Is the culture of this practice part of the jQuery community, or is it a larger javascript phenomenon?

Can you recommend a guide to building tools that utilize this methodology?


Yep it's called the Observer design pattern. It's not isolated to JQuery or even JavaScript for that matter. Many design patterns can be implemented into most programming languages.

DevShop is a framework of design patterns for javascript. Their Observer pattern looks like this:

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});
        }
    });
})();

OBSERVABLE

(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});
        }
    });
})();

You can read more about the Observer design pattern here: http://en.wikipedia.org/wiki/Observer_pattern

0

精彩评论

暂无评论...
验证码 换一张
取 消