Arbiter.js - A full-featured javascript pub/sub (Observer) implementation by Matt Kruse
Description: Arbiter.js is a light-weight, library-agnostic javascript implementation of the pub/sub pattern, written by Matt Kruse. It allows objects on your page to be de-coupled, and communicate with each other through messages. This leads to a cleaner, more easily understood design, and easier maintenance.

Download source: Arbiter.js
Version:
Updated:
This work is in the public domain and may be used in any way, for any purpose, without restriction.
Support:

Arbiter.js is a light-weight, library-agnostic javascript implementation of the pub/sub pattern, written by Matt Kruse. It allows objects on your page to be de-coupled, and communicate with each other through messages. This leads to a cleaner, more easily understood design, and easier maintenance.

For example, if the user changes a value on one part of the page, it can publish a message saying which action was taken. Other parts of the page can subscribe to that action, and do something when it happens. But the first interaction doesn't have to know anything about the second. It just announces what happened, and anyone who cares can act on it.

Example

A simple code example might look like this:

// In the "notifications" widget, I want to do something when new mail arrives Arbiter.subscribe("email/new", function(data) { document.getElementById('notification').innerHTML = "New email from "+data.from; }); // This code is called by the system that detects incoming email Arbiter.publish("email/new", {from:"Bob"});
Console:
Arbiter.subscribe('click/*', null, document.getElementById('console'), function(data,msg) { this.innerHTML += msg+"<br>"; });

Here is a simple working example:

Method Summary
Arbiter.publish
Arbiter.publish( msg [, data [, options] ] ) Returns: true on success, false if any subscriber has thrown a js exception
Arbiter.subscribe
Arbiter.subscribe( msg, func ) Arbiter.subscribe( msg, options, func ) Arbiter.subscribe( msg, options, context, func ) Returns: subscription id or [id1,id2] if subscribing to multiple messages
Arbiter.unsubscribe
Arbiter.unsubscribe( subscription_id )
Arbiter.resubscribe
Arbiter.resubscribe( subscription_id )
Arbiter.create
Arbiter.create()
How To
Publish a simple message
Arbiter.publish( 'component/msg' );
A message may be in any format, but may not contain [ ,*]. A structure like a/b/c is recommended by convention, to allow messages to be categorized.
Subscribe to a message
Arbiter.subscribe( 'component/msg', function() { } );
Subscriber functions will be passed the following arguments:

- published_data: Any data that the publisher has passed along
- message: The message text that triggered the notification (useful if a subscriber function can handle multiple messages)
- subscriber_data: An object (initially empty) that will be passed between subscribers. This may be useful if you would like subscribers to send context or additional data to subsequent subscribers

The value of "this" to be used within the function may be set in the subscribe() method itself.
Pass data to subscribers
Arbiter.publish( 'component/msg', {"data":"value"} );
Publishers can pass data to subscribers that contains details about the message.
Force message bubbling
Arbiter.publish( 'component/msg' , null, {cancelable:false} );
By default, subscribers can return "false" to prevent subsequent subscribers from receiving the message. By passing cancelable:false in the options, the publisher can prevent canceling.
Allow late susbcribers to be notified of past messages
Arbiter.publish( 'component/msg' , null, {persist:true} );
By default, subscribers only receive notifications about messages sent after they subscribe. But for some events, like "system initalized" that may fire only once, it can be useful to allow subscribers to that message to get fired if the message has already been sent. If the publishers wants subscribers to be notified of this message even if they subscribe later, setting the persist flag will do that.
Fire subscribers asynchronously
Arbiter.publish( 'component/msg', null, {async:true} );
By default, subscribers are notified and their functions are run synchronously, so the publish() function doesn't return until all subscribers have finished. If you wish to notify the subscribers but return from the publish() call before the subscriber functions execute, use asynchronous mode. Note: Subscribers cannot cancel asynchonous messages, because the subscribers are executed independently using setTimeout()
Subscribe to multiple messages at once
Arbiter.subscribe( 'component/msg, component/msg2', function() { } ); or Arbiter.subscribe( ['component/msg','component/msg2'], function() { } );
The second argument to the subscriber function is the message, so you can distinguish which messages you are handling.
Subscribe to multiple messages using a wildcard
Arbiter.subscribe( 'component/*', function() { } );
This can be useful for handling all messages of a certain component or category. If you take care when naming your messages, using wildcards can help avoid subscribing to multiple individual messages and needing to update as new messages are added.
Subscribe to ALL messages
Arbiter.subscribe( '*', function() { } );
This can be useful for logging, for example. You can create a separate message logger that receives all messages and displays them in a debug window.
Set subscriber priority
Arbiter.subscribe( 'msg', {priority:10}, func(){} ); Arbiter.subscribe( 'msg', {priority:20}, func(){} ); // Called first!
By default, all subscribers have a priority of 0. Higher values get higher priority and are executed first. Negative values are allowed.
Execute a subscriber asynchronously
Arbiter.subscribe( 'msg', {async:true}, func(){} );
A subscriber can be set to execute asynchronously, even if the message wasn't published as async. If a subscriber knows that it will do some heavy calculations, for example, it can force itself to be async so it won't interfere with the execution of other subscribers.
Ignore persisted messages
Arbiter.subscribe( 'msg', {persist:false}, func(){} );
If a message was persisted, a subscriber will be notified of it even if was sent in the past. If your subscriber is not interested in any past messages that may have been persisted, you can force them to be ignored.
Set the value of "this"
Arbiter.subscribe( 'msg', null, document.getElementById('x'), function() { this.innerHTML = "Message handled!"; } );
When executing the subscriber function, the value of "this" in the function can be specified at subscription time.
Unsubscribe from messages
var subscription_id = Arbiter.subscribe( 'msg', function(){} ); Arbiter.unsubscribe( subscription_id );
Unsubscribing simply sets a flag which prevents the subscriber from executing, in case you want to re-subscribe later.
Re-subscribe to messages
var subscription_id = Arbiter.subscribe( 'msg', function(){} ); Arbiter.unsubscribe( subscription_id ); Arbiter.resubscribe( subscription_id );
After unsubscribing, you can later re-subscribe to begin receiving messages again
Create a new message handler
var MyController = Arbiter.create()
This creates a separate Arbiter instance. If you want to have different message handlers entirely, for example, this will allow for that. Messages sent to the new object will not be shared with the default Arbiter object. You may create as many arbiters as you wish, and they will all operate independently.
Source
/* Arbiter.js by Matt Kruse http://ArbiterJS.com - See site for documentation This work is in the public domain and may be used in any way, for any purpose, without restriction. */ var Arbiter = (function () { var create_arbiter = function () { var subscriptions = {}; var wildcard_subscriptions = {}; var persistent_messages = {}; var id_lookup = {}; var new_id = 1; return { 'version':'1.0' ,'updated_on':'2011-12-19' ,'create': function() { return create_arbiter(); } ,'subscribe': function() { var msg, messages, subscription_list, persisted_subscription_list, subscription, func, options={}, context, wildcard=false, priority=0, id, return_ids=[]; if (arguments.length<2) { return null; } messages = arguments[0]; func = arguments[arguments.length-1]; // Function is always last argument if (arguments.length>2) { options = arguments[1] || {}; } if (arguments.length>3) { context = arguments[2]; } if (options.priority) { priority = options.priority; } if (typeof messages=="string") { messages = messages.split(/[,\s]+/); } for (var i=0; i<messages.length; i++) { msg = messages[i]; // If the message ends in *, it's a wildcard subscription if (/\*$/.test(msg)) { wildcard = true; msg = msg.replace(/\*$/,''); subscription_list = wildcard_subscriptions[msg]; if (!subscription_list) { wildcard_subscriptions[msg] = subscription_list = []; } } else { subscription_list = subscriptions[msg]; if (!subscription_list) { subscriptions[msg] = subscription_list = []; } } id = new_id++; subscription = {'id':id,'f':func,p:priority,self:context,'options':options}; id_lookup[id] = subscription; subscription_list.push ( subscription ); // Sort the list by priority subscription_list = subscription_list.sort( function(a,b) { return (a.p>b.p?-1:a.p==b.p?0:1); } ); // Put it back in after sorting if (wildcard) { wildcard_subscriptions[msg] = subscription_list; } else { subscriptions[msg] = subscription_list; } return_ids.push(id); // Check to see if there are any persistent messages that need // to be fired immediately if (!options.persist && persistent_messages[msg]) { persisted_subscription_list = persistent_messages[msg]; for (var j=0; j<persisted_subscription_list.length; j++) { subscription.f.call( subscription.self, persisted_subscription_list[j], {persist:true} ); } } } // Return an array of id's, or just 1 if (messages.length>0) { return return_ids; } return return_ids[0]; } ,'publish': function(msg, data, options) { var async_timeout=10,result,overall_result=true,cancelable=true,internal_data={},subscriber, wildcard_msg; var subscription_list = subscriptions[msg] || []; options = options || {}; // Look through wildcard subscriptions to find any that apply for (wildcard_msg in wildcard_subscriptions) { if (msg.indexOf(wildcard_msg)==0) { subscription_list = subscription_list.concat( wildcard_subscriptions[wildcard_msg] ); } } if (options.persist===true) { if (!persistent_messages[msg]) { persistent_messages[msg] = []; } persistent_messages[msg].push( data ); } if (subscription_list.length==0) { return overall_result; } if (typeof options.cancelable=="boolean") { cancelable = options.cancelable; } for (var i=0; i<subscription_list.length; i++) { subscriber = subscription_list[i]; if (subscriber.unsubscribed) { continue; // Ignore unsubscribed listeners } try { // Publisher OR subscriber may request async if (options.async===true || (subscriber.options && subscriber.options.async)) { setTimeout( (function(inner_subscriber) { return function() { inner_subscriber.f.call( inner_subscriber.self, data, msg, internal_data ); }; })(subscriber), async_timeout++ ); } else { result = subscriber.f.call( subscriber.self, data, msg, internal_data ); if (cancelable && result===false) { break; } } } catch(e) { overall_result = false; } } return overall_result; } ,'unsubscribe': function(id) { if (id_lookup[id]) { id_lookup[id].unsubscribed = true; return true; } return false; } ,'resubscribe': function(id) { if (id_lookup[id]) { id_lookup[id].unsubscribed = false; return true; } return false; } }; }; return create_arbiter(); })();