A simple, content-based, publisher subscriber pattern implemented in javascript.
A simple, private queuing class for storing content for subscribers. The constructor does not take an argument.
Example
var queue = new Queue();
The private array content is stored in before it's processed. The queue is first in, first out.
This flag allows setTimeout() and setInterval() events to be processed sequentially.
A privileged method (closure) to push content onto its private queue. Takes an object as an argument. No validation is done on the object. The object is the message the publisher is broadcasting to the subscribers.
Example
queue.push( { 'Sample message.' } );
A priviledged method (closure) to shift content from the queue. Takes no arguments and returns the object stored at the first position in the queue.
**Example**// This is the pattern used inside of a callback for synchronous
// processing of the queue.
var message = queue.shift();
if (message) {
console.log( message );
queue.finish();
}
The algorithm here is if there is no callback currently processing the queue and there are items in the queue, then mark the queue as being processed and return the next item from the queue. Otherwise, there's nothing to see here.
A priviledged method (closure) that sets the processing flag to false. I don't know why I was hellbent on making this private, but this is just sugar coating for telling the queue the currently executing callback is done. See example for Queue.shift.
Creates a new PubSub object.
Example
var pubsub = new PubSub()
This object holds the subscribers and queues.
The unique id of each subscriber and becaomes the token by which subscribers can be identified and deleted. This is only used when deleting a subscriber.
#### PubSub.getSubscribers() A priviledged method (closure) that returns the list of subscribers and queues associated with the given key.Example
var topicSubscribers = pubsub.getSubscribers( 'Topic' );
// This is currently only used to delete subscribers.
var allSubscribers = pubsub.getSubscribers();
Example
pubsub.setSubscriber( 'Topic', {
callback: function () { console.log( arguments ) }
});
Example
var token = pubsub.subscribe( 'Topic', {
callback: function () { console.log( arguments ) }
});
pubsub.deleteSubscriber( token );
Example
pubsub.broadcast( 'Topic', {
callback: function () { console.log( arguments ) }
});
Example
var token = pubsub.subscribe({
topic: 'Topic',
callback: function () { console.log( arguments ) }
});
Example
pubsub.publish({
do: 'A needle pulling thread'
});
Example
pubsub.unsubscribe( token );