オブザーバーパターン

 var Listener = function(name, subject){
         function update(evt) {
             evt(this);
         }
         var obj = {
             name: name,
             update: update
         };
         if (subject) {
             subject.register(obj);
         }
         return obj;
 };
 var Subject = function(){
     var listeners = [];
     function notify(evt) {
         for (var i = 0; i < listeners.length; i++) {
             listeners[i].update(evt);
         }
     }
     function register(listener) {
         listeners.push(listener);
     }
     function unregister(listener) {
         var buf = [];
         for (var i = 0; i < listeners.length; i++) {
             if (listener != listeners[i]) {
                 buf.push(listeners[i]);
             }
         }
         listeners = buf;
     }
     return {
         listeners:  listeners,
         notify:     notify,
         register:   register,
         unregister: unregister
     };
 };
 var s = Subject();
 l1 = Listener('LISTENER1', s);
 l2 = Listener('LISTENER2', s);
 l3 = Listener('LISTENER3');
 s.notify(function(obj){ console.log('hello, ' + obj.name)});
 console.log('---');
 s.register(l3);
 s.notify(function(obj){ console.log('hello, ' + obj.name)});
 console.log('---');
 s.unregister(l2);
 s.notify(function(obj){ console.log('hello, ' + obj.name)});
 hello, LISTENER1
 hello, LISTENER2
 ---
 hello, LISTENER1
 hello, LISTENER2
 hello, LISTENER3
 ---
 hello, LISTENER1
 hello, LISTENER3

補足

Subjectがnotify()でListner群をupdate()する際にsetTimeout()でくるんであげると、update()処理が重くてもメインスレッドに影響を与えないので、あるケースでは便利。


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2012-02-06 (月) 18:50:17