Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rebinding exports in d3.js v4

I'm creating a map using the modules system. I'm more or less used to D3.js v3 but I am still getting used to v4.

I am trying to add a dispatch but I don't know how to rebind the exports in V4, as this function is not available now.

So for my dispatch (_dis) and my particular event ("changetype"), the rebind in d3 v3 would be right before returning the exports, for example:

d3.mapDots = function (districts){

   var _dis = d3.dispatch('changetype');

   (...)

   exports.color = function(_c){
       if(!arguments.length) return color;
       color = _c;
       return this;
   };    

   d3.rebind(exports,_dis,"on");
   return exports
   };

Does anyone know how to do this in v4? I've been trying dispatch.apply but it doesn't work.

Thanks!

like image 646
Irene Avatar asked Jul 12 '16 15:07

Irene


People also ask

How do I bind data to a selection in D3?

When using D3.js, we often bind individual data values to the visual elements in a selection and then modify the appearance of the visual elements to reflect the data. To bind data to the elements in a selection we call selection.data ( [data [, key]]) on the selection.

What is the use of D3 in HTML?

D3 allows you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document. For example, you can use D3 to generate an HTML table from an array of numbers. Or, use the same data to create an interactive SVG bar chart with smooth transitions and interaction.

What are the functions of data in D3?

Yet styles, attributes, and other properties can be specified as functions of data in D3, not just simple constants. Despite their apparent simplicity, these functions can be surprisingly powerful; the d3.geoPath function, for example, projects geographic coordinates into SVG path data.

How do I mutate a node in D3?

D3 provides numerous methods for mutating nodes: setting attributes or styles; registering event listeners; adding, removing or sorting nodes; and changing HTML or text content. These suffice for the vast majority of needs. Direct access to the underlying DOM is also possible, as each D3 selection is simply an array of nodes.


1 Answers

Good question. Looks like the dispatch object has somewhat changed, and that d3.rebind no longer exists. Because the latter is gone, it appears that there's no way to "copy" (via d3.rebind) the .on() method. Instead you must implement your own. See here how bostock implemented d3-brush.

I put together this jsFiddle to demonstrate how to achieve with D3 v4 what you're asking.

The important bit is implementing the .on method:

instance.on = function() {
  var value = dispatcher.on.apply(dispatcher, arguments);
  return value === dispatcher ? instance : value;
}

And, dispatching is like this

dispatcher.call("was_clicked", this, "Hello, Foo!");
like image 199
meetamit Avatar answered Sep 28 '22 05:09

meetamit