Home

Awesome

Backbone.Courier

A tiny library that bubble events ("messages") up your backbone.js view hierarchy.

How it works

Instead of using view.trigger(), use view.spawn( messageName, [data] ) to spawn a message.

this.spawn( "selected", this.model );

The message is triggered, just like a normal backbone event, and in addition, it will automatically bubble up you view hierarchy. The view's parent can then "handle" the message and / or pass it to the parent's own parent, and so on. The DOM tree is used to determine the view hierarchy.

Here is an example of a view that both spawns a message to its ancestors, and handles a message from its children.

MyViewClass = Backbone.View.extend( {
	initialize : function() {
		Backbone.Courier.add( this );  // add courier functionality to this view
	}

	events : {
		"click div.close-box" : "_closeBoxClicked"
	},

	// "handle" the "selected" message from a child view.
	onMessages : {
		"selected" : "_onChildSelected"
	}

	_onChildSelected : function( data, source, messageName ) {
		alert( "My child view just spawned the 'selected' message." );

		// the three arguments to a message handler are:
		// 1) any application defined data that has been supplied:
		console.log( data ); // outputs the second argument to `spawn`

		// 2) the child view object that spawned or passed this message
		assert( source instanceof Backbone.View );

		// 3) the name of the message (i.e. first argument to `spawn`)
		assert( messageName === "selected" );
	}
	
	// spawn a message that can be handled by our own parent
	_closeBoxClicked : function() {
		this.spawn( 'closeBoxClicked' );
	}
}

Methods and Property reference

Public API index


<a name="add"></a>Backbone.Courier.add( view )

Adds courier methods and behavior to view. To add courier functionality to all of your views, just wrap Backbone.View.initialize:

var oldInitialize = Backbone.View.prototype.initialize;
Backbone.View.prototype.initialize = function() {
	Backbone.Courier.add( this );
	return oldInitialize.apply( this, arguments );
};

<a name="spawn"></a>view.spawn( messageName, [data] )

The spawn method generates a new message and passes it to the view's "parent", i.e. the closest ancestor view in the DOM tree. (It also calls view.trigger( messageName, data ) so that you can listen to the message as you would a normal Backbone event.) The parent view can "handle" this message, taking some action upon its receipt, by including an entry for this message in its onMessages hash, or it can pass this message to its own parent, using its passMessages property. In this manner the message may bubble up the view hierarchy, as determined (by default) by the DOM tree.

messageName is the name of the message being spawned. The name is used in the onMessages and passMessages properties of ancestor views to handle or pass the message further up the view hierarchy, respectively.

data is application defined data that will be available to this view's ancestors when handling or passing this message.

Round trip messages

If messageName ends in !, the message is considered a "round trip message". Round trip messages are special in that they return values. That is, the spawn() method will return the value returned by the first (and only) method that handles the message. Using round trip messages, views can obtain dynamic information about their environment that, because it is dynamic, can not be passed in through configuration options. Round trip messages are special in that they will continue to be passed up the hierarchy until they are handled - regardless of the value of each intermediate view's passMessages property. If they are not handled, spawn() returns undefined.

<a name="onMessages"></a>view.onMessages

The onMessages hash is the means by which a parent view can take action on, or "handle", messages received from its children. Entries in the onMessages hash have the format:

"messageName source" : callback
<ul> <li>The <code>messageName</code> portion is matched against the name of the messages that are received.</li> <li>The <code>source</code> portion can be used to match only messages that come from a particular child view. In order to map the <code>source</code> name to a particular child view, by default Backbone.Courier expects a hash of child views to be stored in <code>view.subviews</code>, the keys of the hash being the names of the child views, and the values references to the child view objects. You can create this hash yourself, but an easier approach is to use the <a href="Backbone.Subviews">Backbone.Subviews</a> mixin, which will automatically create it for you. (You may also override <code>view._getChildViewNamed()</code> to customize how <code>source</code> mapped to child view objects.)</li> <li>The "callback" portion determines what is done when a matching message is received. Just like Backbone's events hash, you can either provide the callback as the name of a method on the view, or a direct function body. In either case, the callback is invoked with three arguments: <ol> <li><code>data</code> is an application defined data object, as provided the in second argument to <code>view.spawn()</code></li> <li><code>source</code> is the child view object that spawned or passed this message to this view.</li> <li><code>messageName</code> is the name of the message</li> </ol> </li> </ul>

Example entries in the onMessages hash:

onMessages : {
	"focused" : function( data, source ) {
		// handle the "focused" message
		alert( "child view focused" );
		console.log( source ); // the child view that spawned or passed this message
	},

	// when the "selected" message from the resourcesCollectionView child view
	// is received, call the _onResourceSelected method on this view
	"selected resourcesCollectionView" : "_onResourceSelected",

	"giveMeInfo!" : function() {
		// handle the "giveMeInfo!" round trip message. return contents
		// of `value` to the view that spawned the message,
		// as the return value of the view.spawn() method
		var value = this._calculateDynamicValue();
		return value;
	}
},

_onResourceSelected : function( data ) {
	// handle the selected message from the resourcesCollectionView child view
}

<a name="passMessages"></a>view.passMessages

The passMessages property is used to pass messages received from a child view further up the view hierarchy, to potentially be handled by a more distant ancestor. If the property is false which is the default, no messages are passed through the view. If the proerty is true, all (unhandled) messages are passed through the view. If the property is an array, only messages with the names it contains will be passed through. If / when the message is eventually handled further up the hierarchy, the source of the message will be the view from which it was originally spawned.

Internal view methods that may be overridden

The following methods may be overridden to customize Backbone.Courier for your environment. To override one of the methods, attach your own version of the method to your view objects either before or after calling Backbone.Courier.add().

view._getParentView()

view._getParentView() is an internal method that returns a view's "parent view". You may supply your own version of this method on your view objects (which will override the default implementation) if you want to provide a custom means to determine a view's parent. The default implementation determines a view's parent by its position in the DOM tree, scanning the tree for the closest parent that has a Backbone view in $( el ).data( "view" ). This data value is set on each view's DOM element automatically by Backbone.Courier.

Note: The default implementation of '_getParentView' depends on jQuery's or Zepto's $.parent() and $.data() methods, which is the only dependency on a DOM library or tree in Backbone.Courier.

view._getChildViewNamed( childViewName )

view._getChildViewNamed( childViewName ) is an internal method that is used to resolve the child view names optionally supplied in the source part of the onMessages hash. You may supply your own version of this method on your view objects in order to store child views in a location other than the default view.subviews[ childViewName ].

Encapsulated Views

Although Backbone.Courier is a simple library with a very small footprint, its use significantly improves encapsulation in the view layer. Encapsulation makes modules easy to conceptualize, maintain and test. Backbone views that are encapsulated, and Backbone applications built from encapsulated views, have these same characteristics. But what do encapsulated views look like and how does courier help? Here's our vision:

NOTE: You can use Backbone.Courier with Backbone.Subviews and Cartero / Parcelify for a completely modularized backbone.js experience.

Dependencies

Change log

v4.0.0

v3.0.0

v1.0.0

v0.6.1

v0.6.0