Skip to content

available lifecycle events

jacobbroberg edited this page Oct 22, 2014 · 3 revisions

Lifecycle Events - Which ones are available?

As we saw in the What are lifecycle events guide, there are 4 lifecycle events. As soon as data is bound to a selection, the events trigger in the following order:

  • update - called for all data elements that already exist and are bound
  • enter - called for all new data elements that are being bound for the first time and have not been rendered
  • merge - called for all of the above elements (the updated and merged)
  • exit - called for all the elements for which the data is no longer in the bound data

When defining transitions for the lifecycle events, you can attach to the following events:

  • update:transition
  • enter:transition
  • merge:transition
  • exit:transition

Binding to a lifecycle event

Binding to a lifecycle event happens on a layer. There are two ways to attach lifecycle events to a layer:

  1. During creation of the layer
  2. At any other point after the layer has been created.

Defining lifecycle events during layer creation:

You can add lifecycle events using the events property that can be set on the object passed to the layer() function as the third argument.

The key should be the lifecycle event, and the value is the callback. Note that the context of the callback (the this keyword) is the d3 selection. You can always get a reference back to the chart (if you need access to an API function you defined, for example,) by calling this.chart() inside your callbacks.

d3.chart("CircleChart", {
  initialize: function() {
    
    this.layer("circles", this.base.append("g"), {
      dataBind: function(data) {
        return this.selectAll("circle")
          .data(data);
      },
      insert: function() {
        return this.insert("circle")
          .attr("cy", 100)
          .attr("r", 4)
          .style("fill", "red");
      },
      events : {
        enter : function() {
          return this.attr("cx", function(d) { 
            return d; 
          });
        }
      }
    });
  }
});

Adding lifecycle events after layer creation

d3.chart("CircleChart", {
  initialize: function() {
    
    this.layer("circles", this.base.append("g"), {
      dataBind: function(data) {
        return this.selectAll("circle")
          .data(data);
      },
      insert: function() {
        return this.insert("circle")
          .attr("cy", 100)
          .attr("r", 4)
          .style("fill", "red");
      }
    });

    this.layer("circles").on("enter", function() {
      return this.attr("cx", function(d) { 
        return d; 
      });
    });
  }
});