Skip to content

Instantly share code, notes, and snippets.

Last active September 26, 2016 20:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save larsvers/16d02efe0c6b0d640da9f600c81cda16 to your computer and use it in GitHub Desktop.
mnml merge
license: mit

.merge() in pants

V4 swivels off a touch of mysticism from the enter and update selection. When we called the update selection in V3.x it did the job for both enter and update. So all specs you wrote for the update selection were automatically applied to the enter selection. The enter selection wasn't immutable - as in: the elements in the enter selection could be changed from outside, with a data-update for example.

V4 changes that and the enter selection becomes immutable. In simple words: you can modify the enter selection in place and you can modify the update selection in place. But you can't modify the update selection and assume the enter selection will be automatically updated. No no no. Here we need merge. It takes enter selection and update selection and chucks them both into a pot.

If you load this page, enter and update will be seperate. Hence, the numbers will not be tomato-coloured as after loading the page all elements were new, so we only see modifications to enter selection.

When we hit the button, we invoke the same update selection, but now with merge. By using the .merge([selection]) method on the update selection we combine all elements from the enter and the update selection. Any modifications will now apply to both selections.

Much cleverer put:

Selectig data

Find '.merge' here

The general idea

Immutability in JS

Built with

<!DOCTYPE html>
<meta charset="utf-8">
<script src=""></script>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
div { margin: 31px; }
<div id="container"></div>
<button>update without merge</button>
var data = [1,2,3,4,5];
var join ='#container').selectAll('div')
var enter = join.enter()
.html(function(d) { return d; });
var update ='color', 'tomato');'button').on('mousedown', function() {
update = join.merge(enter).style('color', 'tomato');'update with merge');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment