Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d3
method chaining
javascript

What is method chaining in D3?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

svg viewer

Overview

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.

Example

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.

svg viewer

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.

svg viewer

Moving forward, the text() just adds text to the <p> element block.

svg viewer

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.

svg viewer

RELATED TAGS

d3
method chaining
javascript
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring