Skip to content

Instantly share code, notes, and snippets.

@larsvers
Last active September 26, 2016 20:19
Embed
What would you like to do?
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 blockbuilder.org

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