It’s been near a year and a half, but I’m finally working on a Backbone.js project again! I’m excited… the MarionetteJS team has been kicking butt since I handed off the keys to the castle, and there’s lot of new things for me to play with. But almost immediately after starting to dive in to this project, I ran in to an annoying problem – one of those things that I believe should be solved for me, instead of requiring me to write a bunch of ugly code over and over and over again. The perfect candidate for an abstraction and add-on.
I found myself wanting an easy way to forward events from one Backbone object, through another, without having to do this everywhere:
The result of my desire is Backbone.fwd – a small library that lets you forward events without having to copy & paste that code pattern!
Backbone.fwd: Basic Usage
The most basic usage of Backbone.fwd requires 2 things:
- Attach the `fwd` method to a Backbone object
- Call the `fwd` method, passing in an object that will raise events
After that, you can subscribe to events on the object that has the fwd method and you will receive events from the child object!
Prefix & Suffix
In addition to simple event forwarding, you can add a prefix and suffix to the event name. This is done with a second parameter being passed in to the fwd method call, specifying the prefix and suffix as values of an object literal.
Now when the child object triggers the “name” event, the parent object will forward this as “pre:name:post”.
In Relation To MarionetteJS
If you’re thinking to yourself “Doesn’t MarionetteJS have this built in to it already?” you’re mostly right. I added this basic feature in to Marionette’s view structure to froward view events through each other. But now I find myself wanting this outside of just views. I want to forward through models, views, controller objects and more. Marionette may end up using this code in the future, but there are no definite plans for this yet.
Simple, Yet Powerful
I love building simple tools like this because they make my life easier. Instead of having to copy & paste a bunch of code over and over and over again, I now have an easy way to extend my objects and provide the functionality needed. Easier still, I can add the fwd method to my application base objects or even to the Backbone objects directly within my application, and I never have to think about it again. It’s just there, ready for me to use in my app.
Check out the Backbone.fwd plugin at the github repository, here: github.com/derickbailey/backbone.fwd
P.S. If you’re interested in learning the *why* as well as the how of building Backbone add-ons and plugins, check out my book Building Backbone plugins. It is THE book on reducing Backbone application boilerplate code, building your own application architecture, and improving your own productivity with Backbone.