2011-07-08 27 views
0

我注意到有很多內置的jQuery的工具,特別是那些使用了某種AJAX的,有掛鉤等的onsubmit,的onComplete等的jQuery的onsubmit,的onComplete等

是否有一個名字爲這個實踐和表徵它的慣例?

這種做法的文化是jQuery社區的一部分,還是更大的JavaScript現象?

你能推薦一個指導建築工具,利用這種方法?

回答

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

你可以閱讀更多有關Observer設計模式在這裏:http://en.wikipedia.org/wiki/Observer_pattern

+0

什麼是搖滾回答,等等快! – jMyles