//Observer class function Observer() { var topics = []; return{ Register:function( topic, func ) { if(!topics[topic]) topics[topic]=[]; // two dimension for store callback func topics[topic].push(func); }, Publish:function( topic, args ) { if ( !topics[topic] ) { console.log('no such topic'); return false; } var subscribers = topics[topic]; for(var i in subscribers) subscribers[i](topic,args); }, UnRegister:function( topic ) { if ( !topics[topic] ) { return false; } topics[topic]=null; } } };如何使用呢?
//How to use var observ = new Observer(); //call back signature (topic,data) var testHandler = function (topics, data) { console.log("1:"+topics + ": " + data); }; var testHandler2 = function (topics, data) { console.log("2:"+topics + ": " + data); }; observ.Register('cal1', testHandler); observ.Register('cal1', testHandler2); observ.Publish('cal1', 'hello world!'); observ.Publish('cal1', ['test', 'a', 'b', 'c']); observ.UnRegister('example1'); observ.Publish('example1', 'hello world!');
------------------
執行結果如下
沒想到使用Javascript寫一個Observer Pattern會如此簡單 ....