D3.js tutorial - Part 4 - Method chaining

Introduction

Method chaining is a syntax for calling several methods in one instruction on the same instance. It can be done if each method returns the current object (this). Here is a typical example of method chaining:

socket().destination(server).data(3.25).send();

Most of the D3.js functions allows method chaining which is commonly used while creating charts with D3.js.

D3.js example

Let's keep the last example of the previous part. In this example, a <h1> element was created, then a text was added and finaly the color was set to red. Here is the previous code:

d3.select('body').append('h1');
d3.select('h1').text('This tag and text has been added with D3.js');
d3.select('h1').style('color', 'red');

This code can be rewritten using method chaining, because each function returns the element selected:

Order of execution

A question still remains, in the following example, which is called first?

d3.method1().method2();

method1() is necessary called before method2(). Otherwise, since method1() is not already called, method2() has no returned object to process. The following example confirms the previous statement where the last method is called in last.

// Method chaining order
d3.select('h1').text('First').text('Second')

In conclusion, methods are called from left to right.

See also


Last update : 10/12/2021