javascript observerパターン
javascript observerパターン
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript
Observer implementation
var pubsub = {}; (function(q) { var topics = {}, subUid = -1; q.publish = function(topic, args) { if (!topics[topic]) { return false; } setTimeout(function() { var subscribers = topics[topic], len = subscribers ? subscribers.length : 0; while (len--) { subscribers[len].func(topic, args); } }, 0); return true; }; q.subscribe = function(topic, func) { if (!topics[topic]) { topics[topic] = []; } var token = (++subUid).toString(); topics[topic].push({ token: token, func: func }); return token; }; q.unsubscribe = function(token) { for (var m in topics) { if (topics[m]) { for (var i = 0, j = topics[m].length; i < j; i++) { if (topics[m][i].token === token) { topics[m].splice(i, 1); return token; } } } } return false; }; }(pubsub));
Subscribing and publishing
var testSubscriber = function( topics , data ){ console.log( topics + ": " + data ); }; // Publishers are in charge of "publishing" notifications about events pubsub.publish( 'example1', 'hello world!' ); pubsub.publish( 'example1', ['test','a','b','c'] ); pubsub.publish( 'example1', [{'color':'blue'},{'text':'hello'}] ); // Subscribers basically "subscribe" (or listen) // And once they've been "notified" their callback functions are invoked var testSubscription = pubsub.subscribe( 'example1', testSubscriber ); // Unsubscribe if you no longer wish to be notified setTimeout(function(){ pubsub.unsubscribe( testSubscription ); }, 0); pubsub.publish( 'example1', 'hello again! (this will fail)' );