I’m seeking a critique of the simple program below, which displays two counters and increments them through a button, using D3.js. In real life of course no one has a need for displaying buttons that increment counters. It’s a stand-in to talk about how to craft the code over the scaffold of a trivial problem.
I would like to remain within function invocations, and to generally fit in seamlessly with D3. In particular, I do not wish to use constructor invocation or prototypal patterns. More concretely, I would like to use neither class
nor new
.
I would also like to avoid constantly asking myself “what is this
in this instant?” by initializing that
, as you see in the code (let’s leave arguing that this
is sometimes entirely compelling for another occasion).
function Incrementer(name, value) { let that = {}; that.init = function() { that.name = name; that.span = d3.select('body') .append('span') .attr('id', '#num' + name) .text(value); } that.init(); that.increment = function() { let i = parseInt(that.span.text()) + 1; that.span .text(i); } return that; } var incrementer1 = Incrementer('one', 10); var incrementer2 = Incrementer('two', 20); function double_increment() { incrementer1.increment(); incrementer2.increment(); } d3.select('#inc') .on('click', double_increment); // d3.select('#inc') // .on('click', incrementer1.increment); // d3.select('#inc') // .on('click', incrementer2.increment);
span { margin-left: 40px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <button id="inc">Increment</button><br />
At this point I’m lacking a nice way to avoid the function double_increment
. Of course without that function—were we to use the commented out pair of on-click handlers instead—we would have a bug. Only one on-click handler can be set. We have no mechanism for adding multiple addEventListener
s.
So to summarize:
- We define
that.init
as our initializer. That seems tidier than letting the initialization code loose in the body of the function. But defining it then immediately calling it seems odd. Can you improve on this? - How would you avoid the ugly
double_increment
function within a D3 program?
that.span.text()
should probably be replaced by that.span.datum
, if I can find the datum in there. But we’d like to avoid duplicating the counter within Incrementer
. This way we do not need to worry about the counter and its view going out of sync. The datum itself, once located, is already a bit of a (necessary) duplication.
The post Seeking the seeds for writing tidy event handlers in JS appeared first on 100% Private Proxies - Fast, Anonymous, Quality, Unlimited USA Private Proxy!.