Created
June 21, 2014 22:15
-
-
Save j0lvera/0689482aeca9e0798768 to your computer and use it in GitHub Desktop.
Pub/Sub Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// # Publish/Subscribe Pattern | |
// | |
// from: http://addyosmani.com/resources/essentialjsdesignpatterns/book/#observerpatternjavascript | |
var pubsub = {}; | |
(function(myObject) { | |
// Storage for topics that can be broadcast | |
// or listened to | |
var topics = {}; | |
// An topic identifier | |
var subUid = -1; | |
// Subscribe to events of interest | |
// with a specific topic name and a | |
// callback function, to be executed | |
// when the topic/event is observed | |
myObject.subscribe = function( topic, func ) { | |
if (!topics[topic]) { | |
topics[topic] = []; | |
} | |
var token = ( ++subUid ).toString(); | |
topics[topic].push({ | |
token: token, | |
func: func | |
}); | |
return token; | |
}; | |
// Publish or broadcast events of interest | |
// with a specific topic name and arguments | |
// such as the data to pass along | |
myObject.publish = function( topic, args ) { | |
if ( !topics[topic] ) { | |
return false; | |
} | |
var subscribers = topics[topic], | |
len = subscribers ? subscribers.length : 0; | |
while (len--) { | |
subscribers[len].func( topic, args ); | |
} | |
return this; | |
}; | |
// Unsubscribe from a specific | |
// topic, based on a tokenized reference | |
// to the subscription | |
myObject.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 this; | |
}; | |
}( pubsub )); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment