Routed Commands for Backbone.js

Here’s a quick fiddle that shows how to route a command between sub-views no matter how they’re nested in the DOM. Basically, when a sub-view is rendered it triggers a subscribe event that’s captured by the application view which then sets a delegate on another sub-view. This other sub-view is the source of the events, e.g. a menu bar.

When the event source sub-view triggers events (e.g. clicking a link), it does so on the delegate. Event names are specified in the HTML using a data-event attribute on the link. Enjoy!

When we initialize the application view, the control (source) and subview (target) are created.

The control view listens to ‘subscribe’ events and sets the delegate subview, then responds to clicks from links with data-event attributes sending them to the delegate subview.

The target view triggers a ‘subscribe’ event, sending itself to the control for delegation and listens for those events described in the control’s view.

Leave a Reply