<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yony K. on Medium]]></title>
        <description><![CDATA[Stories by Yony K. on Medium]]></description>
        <link>https://medium.com/@yonester?source=rss-b0f6b1f94fb1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*BCKdn8prou84ZXeiyaF2fw.png</url>
            <title>Stories by Yony K. on Medium</title>
            <link>https://medium.com/@yonester?source=rss-b0f6b1f94fb1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:18:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yonester/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Unexpected Side Effect of Selections]]></title>
            <link>https://medium.com/@yonester/the-side-effects-of-selections-275fcf3e1183?source=rss-b0f6b1f94fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/275fcf3e1183</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[Yony K.]]></dc:creator>
            <pubDate>Tue, 17 Jan 2017 01:26:28 GMT</pubDate>
            <atom:updated>2017-09-07T16:39:45.144Z</atom:updated>
            <content:encoded><![CDATA[<p>Much of web development involves manipulating the DOM. The process is straightforward: retrieve a reference to DOM elements, then manipulate their attributes.</p><pre>// Plain Javascript<br>document.getElementById(&#39;element&#39;).style.fill =&#39;blue&#39;;</pre><pre>// jQuery<br>$(&#39;#element&#39;).css(&#39;fill&#39;, &#39;blue&#39;);</pre><pre>// D3<br>d3.select(&#39;#element&#39;).style(&#39;fill&#39;, &#39;blue&#39;);</pre><p>But there’s an important assumption we’re making here without realizing it—we assume that selecting an element is a read-only operation. That is, merely retrieving a reference to a DOM node does <em>not</em> modify it.</p><p>In D3 this isn’t always the case.</p><p>Consider the following DOM structure:</p><pre>&lt;<strong>svg</strong> width=&quot;50&quot; height=&quot;50&quot;&gt;<br>  &lt;<strong>circle</strong> r=&quot;20&quot; cx=&quot;25&quot; cy=&quot;25&quot;&gt;&lt;/<strong>circle</strong>&gt;<br>&lt;/<strong>svg</strong>&gt;</pre><p>Then try <a href="https://jsfiddle.net/r2fL9noc/6/">running</a> this code:</p><pre>let <strong>svg</strong> = d3.select(&#39;svg&#39;),<br>    <strong>circle</strong> = d3.select(&#39;circle&#39;);</pre><pre><em>// (1) Bind some data.</em><br><strong>svg</strong>.datum({ color: &#39;blue&#39; });<br><strong>circle</strong>.datum({ color: &#39;red&#39; });</pre><pre><em>// (2) Make the circle red.</em><br><strong>circle</strong>.style(&#39;fill&#39;, d =&gt; d.color);</pre><pre><em>// (3) Does nothing, just selecting stuff.</em><br><strong>svg</strong>.select(&#39;circle&#39;);</pre><pre><em>// (4) Same code as #2, now makes the circle... blue??? </em>😲<br><strong>circle</strong>.style(&#39;fill&#39;, d =&gt; d.color);</pre><p>Try commenting out that seemingly useless second-to-last line to see what’s going on here. Indeed, selecting is <em>not</em> a read-only operation. It seems the <em>select</em> operation causes the circle element to inherit its parent’s data.</p><p>To understand why this design decision was made and why it’s actually useful we first have to remember D3’s most important selling point: the <a href="https://bost.ocks.org/mike/join/">data-join</a> (going forward I’ll assume you’re familiar with this paradigm).</p><p>Consider the <a href="https://jsfiddle.net/ff7ukamL/">following</a>:</p><pre>&lt;ul&gt;<br>  &lt;li&gt;&lt;span&gt;1&lt;/span&gt;&lt;/li&gt;<br>  &lt;li&gt;&lt;span&gt;2&lt;/span&gt;&lt;/li&gt;<br>  &lt;li&gt;&lt;span&gt;3&lt;/span&gt;&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Now let’s bind new data and enter/update/exit as usual:</p><pre>let <strong>li</strong> = d3.select(&#39;ul&#39;)<br>  .selectAll(&#39;li&#39;)<br>  .data([&#39;one&#39;, &#39;two&#39;, &#39;three&#39;]);</pre><pre><strong>li</strong>.exit().remove();</pre><pre><strong>li</strong>.select(&#39;span&#39;)<br>  .text(d =&gt; d);</pre><pre><strong>li</strong>.enter().append(&#39;span&#39;)<br>    .text(d =&gt; d);</pre><p>What would happen if <em>selection</em>.select didn’t propagate data from the parent? We’d need a different method of getting our data from the <em>li</em> to the <em>span</em> element, otherwise the child would have the old data (or no data at all if the DOM was initialized statically). We might also be able to find a clever but awkward access to <em>__data__</em>.</p><p>By allowing data to flow down the selection path, <em>selection</em>.select becomes symmetric with <em>selection</em>.append, the former representing the <em>update</em> portion of the data-join while the latter represents the <em>enter</em>.</p><p>D3 is not a conventional way to think about DOM manipulation, which means that in some cases it requires some retraining of our mental model. And when we make it over this hump, we’re rewarded with a powerful, thoughtfully designed tool to bind data with visual elements.</p><p><em>This concept was explained to me by </em><a href="https://medium.com/u/c918c478bb49"><em>Mike Bostock</em></a><em>, the creator and main maintainer of D3, after I actually filed it as </em><a href="https://github.com/d3/d3-selection/issues/106"><em>a bug</em></a><em> </em>😬<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=275fcf3e1183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transitions Don’t Float]]></title>
            <link>https://medium.com/@yonester/transitions-dont-float-e3a6dee7b1a0?source=rss-b0f6b1f94fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3a6dee7b1a0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <dc:creator><![CDATA[Yony K.]]></dc:creator>
            <pubDate>Thu, 13 Oct 2016 03:34:20 GMT</pubDate>
            <atom:updated>2016-12-16T04:11:36.798Z</atom:updated>
            <content:encoded><![CDATA[<p>What does the following code do?</p><pre>let t = d3.transition()<br>    .delay(100)<br>    .duration(1000);</pre><pre>d3.select(&#39;#box&#39;)<br>    .transition(t)<br>    .attr(&#39;x&#39;, 200);</pre><p><em>Wait! </em>Try to answer before moving on.</p><p>A common mistake is to think that the first line instantiates a “free-floating” transition object that holds some configuration values and can later be applied to selections. It seems reasonable that this is a way to save repetition when multiple selections need to use the same transition values.</p><p>Perhaps the reason this is such a common mistake is that in this example code block the resulting behavior is actually correct. However, we may run into cases where the behavior isn’t expected.</p><pre>let t = d3.transition()<br>    .delay(100)<br>    .duration(1000);</pre><pre>setTimeout(() =&gt; {<br>  d3.select(&#39;#box&#39;).transition(t).attr(&#39;x&#39;, 200);<br>}, 2000);</pre><p>If you <a href="https://jsfiddle.net/611ybvcr/">run this code</a>, you might be surprised to see that the transition doesn’t use the configuration values—the box moves too fast. In the future you may be even more surprised when this code actually <a href="https://github.com/d3/d3-transition/issues/59">throws an error</a>!</p><h3>Inheriting Transitions</h3><p>To understand what’s really happening here, look no further than the d3-transition API docs under <a href="https://github.com/d3/d3-transition/blob/master/README.md#transition"><em>d3.transition([name])</em></a>:</p><blockquote>Returns a new transition on the root element, document.documentElement, with the specified <em>name</em>.</blockquote><p>Ah huh! So the first line actually fires off a new transition on the root element. Its similar to,</p><pre>let t = d3.select(document).transition()<br>    .delay(100)<br>    .duration(1000);</pre><p>Notice we’re not using this transition to do anything. No attributes or styles are modified, we just start the timer.</p><p>And now for the second part where we select ‘<em>#box’</em> and apply the transition, let’s look at <a href="https://github.com/d3/d3-transition/blob/master/README.md#selection_transition"><em>selection.transition([name])</em></a>:</p><blockquote>…the timing of the returned transition is inherited from the existing transition of the same id on the nearest ancestor of each selected element.</blockquote><p>So after we created and started a new transition, we inherited the <strong>current</strong> transition timing (not the configuration values) from the document element. That’s why using <em>t</em> after two seconds no longer works—the transition on the root element is over so there’s no timing to inherit!</p><h3>Reusing Transitions</h3><p>So if we can’t use transition instances to share configuration values, how do we reuse values? Transitions, like selections, can be passed into functions via <em>.call()</em>. So we can create a function that sets transition values with fixed parameters as follows:</p><pre>function delayedTransition(t) {<br>  return t.delay(100).duration(1000);<br>}</pre><pre>d3.select(&#39;#box&#39;).transition()<br>    .call(delayedTransition)<br>    .attr(&#39;x&#39;, 200);</pre><pre>setTimeout(() =&gt; {<br>  d3.select(&#39;#box2&#39;).transition()<br>      .call(delayedTransition)<br>      .attr(&#39;y&#39;, 200);<br>}, 2000);</pre><p>Now we can create several types of transition profiles and apply them around the app to various selections. So if you have many transitions that share parameters but are dispatched at different times, modifying configurations this way becomes trivial.</p><p>The important take away is that transitions are not free floating objects; they are applied to selections (sometimes implicitly) and begin immediately. In the solution above a new transition is created for each selection. We simply factor out the configuration piece for easy reusability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3a6dee7b1a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bundling With Rollup—The Basics]]></title>
            <link>https://medium.com/@yonester/bundling-with-rollup-the-basics-b782b55f36a8?source=rss-b0f6b1f94fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b782b55f36a8</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[rollup]]></category>
            <dc:creator><![CDATA[Yony K.]]></dc:creator>
            <pubDate>Tue, 23 Aug 2016 20:21:12 GMT</pubDate>
            <atom:updated>2018-01-17T05:13:52.838Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re writing a module in Node, chances are you’re using CommonJS syntax that looks like this:</p><pre>// sayhi.js<br>var d3 = require(&#39;d3&#39;);</pre><pre>function sayHi() { <br>  d3.select(&#39;body&#39;).html(&#39;hey you guuuuys!&#39;);<br>}</pre><pre>module.exports = sayHi;</pre><p>To run this code in the browser, you need browserify or webpack to create a bundle that includes your code and external libraries in a file that browsers understand.</p><pre>// index.js<br>var sayHi = require(&#39;./sayhi&#39;);<br>sayHi();</pre><pre>// Terminal<br>$ browserify index.js &gt; bundle.js</pre><pre>// index.html<br>&lt;script src=&quot;bundle.js&quot;&gt;&lt;/script&gt;</pre><p>In the process you can also use transforms to convert ES6 syntax to ES5, and a handful of other things. I’m simplifying of course, but this pretty much captures the status quo.</p><p>Write code ↦ create a bundle ↦ run code in the browser.</p><p>But CommonJS syntax has its <a href="https://github.com/rollup/rollup/wiki/ES6-modules#whats-so-great-about-es6-modules">limitations</a>, and in any case ES6 introduces a new <a href="http://jsmodules.io/">module syntax</a> that allows for some great flexibility and better optimization. Unfortunately, neither Node nor browsers currently support this syntax so we need a tool to convert it either to require() for Node, or a browser bundle.</p><p><em>Side note: extolling the virtues of ES6 modules is beyond the scope of this post. Going forward I’m going to assume you’re interested in making the switch and focus on how to do it.</em></p><h3>Rollup</h3><p><a href="http://rollupjs.org/">Rollup</a> is similar to Browserify in that it creates a bundle that includes your code, external libraries (like D3), and optionally performs some inline transforms. The main difference is that it expects files to be written in the ES6 module format.</p><pre>// input<br>import * as d3 from &#39;d3&#39;;</pre><pre>// output -- commonJS<br>var d3 = require(&#39;d3&#39;);</pre><pre>// output -- IIFE (browser-friendly function)<br>(function (d3) { &#39;use strict&#39;; }(d3));</pre><p>As with most tools, there are several ways to get from here to there. Here are some of the basic approaches.</p><h3>A First Pass</h3><p>Let’s walk through an example of how you would create a package that uses D3 and transform it into a browser-friendly bundle.</p><pre>$ npm install -g rollup</pre><p>Let’s create a file, say <em>index.js</em>, and enter our code in ES6 module syntax.</p><pre>import * as d3 from &#39;d3&#39;;</pre><pre>export default function sayHi() { <br>  d3.select(&#39;body&#39;).html(&#39;Hey you guuuys!&#39;);<br>}</pre><p>We’re ready to create a bundle. To make it browser-executable, we’ll specify the <em>IIFE</em> output format (Instantly Invoked Function Expression).</p><pre>$ rollup -f iife --name HiSayer -o bundle.js -- index.js<br>Treating &#39;d3&#39; as external dependency<br>No name was provided for external module &#39;d3&#39; in options.globals – guessing &#39;d3&#39;</pre><p>If you look in <em>bundle.js</em> now, you’ll see the converted code.</p><p>The warning messages are telling us that Rollup encountered a call to import an external module called “<em>d3”</em> that it couldn’t locate. Since we didn’t declare explicitly that we want it left out of the bundle, it assumed that it’s going to exist in the global scope and went on with packaging the rest of our code. Incidentally, the reason “d3” wasn’t found is because Rollup does not follow Node’s path resolution algorithm by default. For that we’ll need to use plugins (more on that below).</p><p>If we intend to exclude D3 from our bundle and instead provide it via the global namespace, it’s better to make this explicit.</p><pre>$ rollup --globals d3:d3 &lt;...other options...&gt;</pre><p>We’ll then need to make sure D3 is available to our code.</p><pre>&lt;script src=&quot;https://d3js.org/d3.v4.min.js&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;bundle.js&quot;&gt;&lt;/script&gt;</pre><p>If we <em>do</em> want to bundle D3 along with our code, say to reduce HTTP requests in production, we need to extend Rollup’s capabilities so it can find Node modules the way Node does.</p><h3>Bundling Third-Party Libraries</h3><p>Rollup’s functionality can be extended using <a href="https://github.com/rollup/rollup/wiki/Plugins">plugins</a>. However, we can’t do that via the command line interface. Instead we create a config file and export a configuration object, specifying the same options as before but adding calls to the plugins.</p><p>First, let’s install a plug-in that allows Rollup to find third-party libraries in the <em>node_modules</em> directory.</p><pre>$ npm install --save-dev rollup-plugin-node-resolve</pre><p>Then create <em>rollup.config.js</em>, importing and invoking the plugin before bundling takes place.</p><pre>// rollup.config.js<br>import resolve from &#39;rollup-plugin-node-resolve&#39;;</pre><pre>export default {<br>  input: &#39;index.js&#39;,<br>  output: {<br>    file: &#39;bundle.js&#39;,  <br>    format: &#39;iife&#39;,<br>    name: &#39;HiSayer&#39;<br>  },<br>  plugins: [<br>    resolve({ jsnext: true })<br>  ]<br>};</pre><p>To use this file we simply run Rollup as follows:</p><pre>$ rollup -c</pre><p>If you look in <em>bundle.js</em> now, you’ll see it contains D3 along with our code so our bundle contains all of the code needed to run the app in one place.</p><p>It’s important to note that <strong>this only works because the D3 source code uses ES6 module syntax</strong>. Rollup doesn’t understand require statements. If you need to include other third-party libraries written in CommonJS, try adding <a href="https://github.com/rollup/rollup-plugin-commonjs">rollup-plugin-commonjs</a> to the plugins array; it converts CommonJS syntax to ES6 so Rollup can bundle it.</p><h3>But Wait, There’s More!</h3><p>The bundle we created can be further manipulated by other tools after it’s created. But we can also use Rollup as a bonafide build tool, again using plugins, applying various transforms while creating the bundle. For example, we can <a href="https://gitlab.com/Rich-Harris/rollup-plugin-buble">transpile</a> the code from ES6 syntax or <a href="https://github.com/lautis/rollup-plugin-coffee-script">coffeescript</a> to the ES5 equivalent, run <a href="https://github.com/TrySound/rollup-plugin-eslint">eslint</a> on it, or just display some useful information after each build like the <a href="https://github.com/ritz078/rollup-plugin-filesize">bundle size</a>. The process is the same—install the plugin and add an instance into the <em>plugins</em> array with some config values.</p><p>For more complex scripting Rollup can be incorporated into a build script via it’s <a href="https://github.com/rollup/rollup/wiki/JavaScript-API">Javascript API</a>, or into other build systems like Grunt or Gulp.</p><p>Update: Since I first wrote this article, the folks at Rollup also created a <a href="https://github.com/rollup/rollup-starter-app">starter app</a>. It includes the basic plug-ins you need to get up and running as well as a few nice extras to serve up your project for development and minify the code for production.</p><p><em>A big thanks to </em><a href="http://twitter.com/micahstubbs"><em>@micahstubb</em></a><em>s for proof reading this post and suggesting helpful edits.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b782b55f36a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing Visualizations]]></title>
            <link>https://medium.com/@yonester/testing-transitioning-elements-b065c5fdf64d?source=rss-b0f6b1f94fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b065c5fdf64d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Yony K.]]></dc:creator>
            <pubDate>Wed, 10 Aug 2016 16:17:54 GMT</pubDate>
            <atom:updated>2016-08-18T18:56:39.431Z</atom:updated>
            <content:encoded><![CDATA[<p>When we build visualizations that display a small and predictable data set we can usually get away with Looks-Right-Testing (LRT? Anyone? <a href="https://www.youtube.com/watch?v=uhiCFdWeQfA">Anyone?</a>). Of course all visualizations have to “look right” but when we start dealing with larger, dynamic datasets, or use our visualizations as UI building blocks we need a way to declare our assumptions and safeguard against regression with unit testing.</p><p>To test the visual manipulation parts of our code what we need is a DOM. We could run tests in a browser, but to automate them easily I prefer my build pipeline to remain within Node.</p><p>If you look at some of the D3 <a href="https://github.com/d3/d3-selection/tree/master/test">source code</a>, you’ll see it uses <a href="https://github.com/tmpvar/jsdom">JSDOM</a> to do this. It’s a great project that gives us access to a DOM in Node and works great for creating and removing nodes, and changing attributes. Unfortunately, JSDOM doesn’t support the SVG methods necessary to apply certain transitions, in particular transitions of the <em>transform</em> attribute. So even if you don’t care about testing the transitions themselves, any call to <em>transition.attr(‘transform’, …)</em> in your code will break your test.</p><p>So let’s create a hybrid. We’ll write our tests in Node but then bundle them and hand them off to a headless browser to run them and hand us back the results as they’re executed.</p><h3>Dead Simple Setup</h3><p>Let’s set up a simple environment. I’m using <a href="https://github.com/substack/tape">tape</a> for testing because it’s a zero-configuration, super simple library that just works.</p><pre>$ npm install --save-dev tape</pre><p>Say we want to test this function,</p><pre><em>// movedot.js</em><br>module.exports = function moveDot(selection) {<br>  selection.transition()<br>      .attr(&#39;cx&#39;, d =&gt; d.x)<br>      .attr(&#39;cy&#39;, d =&gt; d.y);<br>}</pre><p>We can set up a test like this,</p><pre><em>// test.js</em><br>let d3 = require(&#39;d3&#39;),<br>    test = require(&#39;tape&#39;),<br>    moveDot = require(&#39;./movedot&#39;);</pre><pre>test(&#39;moveDot() sets dot position according to data&#39;, (t) =&gt; {<br>  let dot = d3.select(&#39;body&#39;)<br>    .append(&#39;svg&#39;)<br>    .append(&#39;circle&#39;)<br>      .attr(&#39;cx&#39;, 0)<br>      .attr(&#39;cy&#39;, 0);</pre><pre>  dot.datum({ x: 10, y: 10 }).call(moveDot);<br>  setTimeout(() =&gt; {<br>    t.equal(+dot.attr(&#39;cx&#39;), 10, &#39;Dot moves to new x coord&#39;);<br>    t.equal(+dot.attr(&#39;cy&#39;), 10, &#39;Dot moves to new y coord&#39;);    <br>    t.end();<br>  }, 260);<br>});</pre><p>Note that we wait for the transition to complete (default duration is 250ms, but we add a bit of padding) and then declare our assertions. We also need to call <em>end()</em> to notify tape this test is done.</p><p>To run this code, we bundle it up and give it to <a href="https://github.com/juliangruber/tape-run">tape-run</a>, a bridge layer between tape and another project called <a href="https://github.com/juliangruber/browser-run">browser-run</a>, which executes code in a browser. It comes with and uses <a href="https://github.com/electron/electron">electron.js</a> by default.</p><pre>$ npm install -g browserify tape-run</pre><p>And now bundle and run.</p><pre>$ browserify test.js | tape-run<br>TAP version 13<br># moveDot() sets dot position according to data<br>ok 1 Dot moves to new x coord<br>ok 2 Dot moves to new y coord</pre><pre>1..2<br># tests 2<br># pass  2</pre><pre># ok</pre><h3>Multiple Transitions</h3><p>The code above works well when we test the state of our code past a single transition. But if we want to test the state past several transitions sequentially we quickly end up with the dreaded Pyramid of Doom as we wait for each transition to complete before asserting and moving on to the next one.</p><pre>dot.datum({ x: 0, y: 0 }).call(moveDot);<br>setTimeout(() =&gt; {<br>  t.equal(...);<br>  <br>  dot.datum({ x: 1000, y: -1000 }).call(moveDot);<br>  setTimeout(() =&gt; {<br>    t.equal(...);<br>    <br>    dot.datum({ x: 0, y: 0 }).call(moveDot);<br>    setTimeout(() =&gt; {<br>      t.equal(...);</pre><pre>      ...🚀</pre><p>We could use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a> but I’ve found a simpler, light-weight syntax already included with D3 to tame this mess.</p><p>Enter <a href="https://github.com/d3/d3-queue">d3-queue</a>! An easy way of executing asynchronous function at a configurable concurrency. In our case we want a perfectly sequential execution so we configure a queue to execute one function at a time.</p><pre>let q = d3.queue(1);</pre><pre>q.defer(callback =&gt; {<br>  dot.datum({ x: 1000, y: -1000 }).call(moveDot);<br>  setTimeout(callback, 260);<br>});</pre><pre>q.defer(callback =&gt; {<br>  t.equal(...);<br>  dot.datum({ x: 0, y: 0 }).call(moveDot); <br>  setTimeout(callback, 260);<br>});</pre><pre>q.defer(callback =&gt; {<br>  t.equal(...);<br>  dot.datum({ x: 10, y: 10 }).call(moveDot);<br>  setTimeout(callback, 260);<br>});</pre><pre>q.await(t.end);</pre><p><em>q.defer()</em> queues up the given function, which the queue then executes only when the previously deferred function completes (again, because we configured concurrency as 1). After making some assertions we set up the next test case and wait for the next transition to complete before calling <em>callback</em>. This signals to the queue that the current function is done and the next deferred function in line can be called. The next function will in turn assert and setup again. Finally, <em>q.await()</em> waits for the queue to deplete before calling a final function with the results. In our case we ignore the results since they are handled by the assertions along the way.</p><h3>Back to Reality</h3><p>To be sure, the example above is quite contrived. With it’s thousands of tests you can feel confident that D3 will handle your transitions properly. The point of this exercise isn’t to test transitions. Rather, it’s to allow you to test code that happens to <em>contain</em> transitions. It allows transitions to pass by so you can get to the parts you actually need to be tested.</p><p>Another strategy would be to separate your transitions into standalone functions that can be more easily stubbed out. This has the advantage of making transitions more generic and reusable in your app, though it might make your code more verbose than you’d like.</p><p>Regardless, you’d do well to separate much of your data manipulation logic from the visual parts. That way you could catch bugs at a granular level before they’re ever translated into DOM elements.</p><p>And for everything else, there’s <a href="https://twitter.com/search?q=%23d3brokeandmadeart">#d3brokeandmadeart</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b065c5fdf64d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On D3 and Arrow Functions]]></title>
            <link>https://medium.com/@yonester/on-d3-and-arrow-functions-b6559c1cebb8?source=rss-b0f6b1f94fb1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6559c1cebb8</guid>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Yony K.]]></dc:creator>
            <pubDate>Fri, 29 Jul 2016 19:27:18 GMT</pubDate>
            <atom:updated>2017-02-01T19:14:31.703Z</atom:updated>
            <content:encoded><![CDATA[<p>D3 implements a useful pattern where functions that operate on selections are given the selected DOM element via <em>this.</em> It allows us to use the selection’s bound data and the DOM element within the same context.</p><pre>selection.on(&#39;mouseenter&#39;, function(d) {<br>  d3.select(this).text(d.name);<br>});</pre><p>This is possible because Javascript allows D3 to bind any object to <em>this</em> when calling our function, primarily via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind"><em>bind()</em></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call"><em>call()</em></a>, or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply"><em>apply()</em></a>.</p><p>When making the switch to ES6, it seems reasonable that we’d want to use the syntactically delectable <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> to replace all our callback functions. Their succinct syntax makes them especially attractive for short, attribute retrieving callbacks, which are quite prevalent in D3-based code.</p><p>However, arrow functions have an additional feature that prevents D3 from passing us a custom <em>this</em> and so our code breaks or leads to the wrong behavior.</p><pre>selection.on(&#39;mouseenter&#39;, (d) =&gt; {<br>  d3.select(this).text(d.name);<br>});</pre><pre>// ➜ 💩</pre><p>The reason for this is a feature called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this">Lexical this</a>. Lexical, in this context, is just a Harvard-degree way of saying static. In the olden days <em>this</em> was determined dynamically based on the way a function was called. It gave us a lot of flexibility, but also required discipline and a good understanding of all the ways in which <em>this </em>could be manipulated. Arrow functions, on the other hand, always determine the value of <em>this</em> from the surrounding context, i.e., statically. This strict definition gives us predictability but it also means it cannot be changed at runtime. So while D3 does attempt to set its value for us, Javascript discards it and uses the lexical reference instead. In the above example it’s possible that <em>this</em> actually refers to the global window object if there is no other surrounding scope, which would explain why it doesn’t work.</p><p>Before you start Googling, let me save you the finger cramp. It’s not possible to change this.</p><p>But there’s another way. The function signature for functions that operate on selections was changed in D3 v4 to include the selection group. From the <a href="https://github.com/d3/d3/blob/master/CHANGES.md#selections-d3-selection">release notes</a>:</p><blockquote>The standard arguments are the element’s datum (<em>d</em>), the element’s index (<em>i</em>), and the element’s group (<em>nodes</em>), with <em>this</em> as the element.</blockquote><p>So now we can use the group along with the provided index to access the current DOM element.</p><pre>selection.on(&#39;mouseenter&#39;, (d, i, nodes) =&gt; {<br>  d3.select(nodes[i]).text(d.name);<br>});</pre><p>Perhaps not quite as elegant, but it lets us keep the best of both worlds and avoid inconsistent function definition syntax. Note that <em>this</em> still points to the DOM element if we choose to use the “classic” function definition as before.</p><p><em>Thanks to </em><a href="https://medium.com/u/a03ef79b873e"><em>Nikolay Dimitrov</em></a><em> for pointing out the updated function definition so that we may have our cake and eat it too.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6559c1cebb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>