オブザーバーパターン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()処理が重くてもメインスレッドに影響を与えないので、あるケースでは便利。 |
|