Marrying Backbone.js and D3.js

When I gave my first talk on this topic a year ago, someone came up to me after and said, “Maybe I don’t understand, but it just doesn’t seem that difficult”. I agree. I don’t think it’s hard to use Backbone and D3 together. But what I think is difficult is to come up with a pattern of using them together well. The two libraries want ownership of a lot of the same things; they both want control of the DOM, and they both want to dictate the data flow.

So who should do what?

For my first attempt, I injected D3 code directly into Backbone Views. I let Backbone dictate the structure and data flow, and let D3 have the DOM.

Then I learned about reusable D3 charts, and the merits of separating Backbone and D3. I let D3 do most of the heavy lifting, taking advantage of its enter-update-exit pattern, and used Backbone as the data store.

It worked well for a lot of my projects, until I started hitting seemingly random bugs on one particular project. It was fascinating.

So for the third time, I kept the reusable D3 charts but gave the power back to Backbone. Instead of letting D3 calculate what to enter or what to exit, I took advantage of Backbone's change, add, and remove events. This seemed to solve the bugs.

I don’t believe there’s one definite answer to “who should do what”. Different projects have different needs, and we should choose the approach that makes the most sense for the particular situation. In that sense, I hope my experiences can help others marry Backbone and D3 in a way that works for them.