D3 objects are configured using a general convention called method chaining. Method chaining is a way to add capabilities to an object in one go. It essentially arms you with the possibility to make your object in just one lengthy statement.
The calls are made from left to right. You can think of it as a naive recursive calling. First, the left-most method is called, which moves on to call the method on its right that expects it to return an object. This chain of calling the method chained on the right continues until the last method on the chain.
Let’s look at the following code snippet:
In the above code, we have used the d3.select()
method to initialize a <body>
tag for our object. This body object will then have methods chained to it that will return an object with added capabilities.
Next, we append another method called append()
. append()
is a special case for method chaining because it creates a new element and returns a selection to it. In our example, it creates <p>
tag. However, it does not return the <p>
tag right away, instead it moves forward on the chain to add more capabilities.
Moving forward, the text()
just adds text to the <p>
element block.
As the method syntax suggests, the attr()
method is used to add attributes to the object. We are using attr()
in our example to add three styling attributes to the <p>
element.
Free Resources