× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

D3.js: Passing the Buck

Jonathan Eunice
Dec 09, 2014
<p>It's often the case in D3.js that your code for adding objects will get really, really long. What started as a simple, static attribute becomes a function dynamically computing an attribute. Then it becomes a complex function trying to make a sophisticated decision on the fly. What started as adding a single element becomes adding that element, plus an outside wrapping element, plus some child elements--each potentially with their own attributes, properties, styles, and included content. The output becomes beautiful, but the code gets messy. A few more changes down the line, complexity bites. Things start to break.</p><p>There are two simple ways to handle this. Both boil down to "passing the buck." First, whenever you have more than a one-line function trying to decide an attribute, you don't have to state that function in-line. You can move it elsewhere ("hoist it"), clarifying both the decision being made and the D3 code creating your objects. </p><p>The second technique is the big gun: Move the entire object creation process into its own function. This is easily done with the <code>.call(fn)</code> method. <code>fn</code> will be called with the current selection, and your call chain can continue cleanly, but within the function. It will be more modular, more easily understood, and often, more reusable.</p>
comments powered by Disqus