Pass DOM element to selection functions
See original GitHub issueCurrently the context of a function passed to selection.attr
(and its sibling operations) is set to the DOM element of the selection. Things get tricky when you want to both use the outer this
and do something with the DOM element. Of course, a var self = this;
before the function solves this.
var self = this;
d3.select('#some-element')
// Completely contrived example of using both this and self:
.attr('class', function() {
return (self.highlightA && this.dataset.a) ? 'highlight' : 'normal';
});
What would be more convenient is if the DOM element was available as a parameter to the function, i.e. (d, i, element)
. This would allow you to use ES6’s arrow functions, which ignore the function’s context.
d3.select('#some-element')
// Completely contrived example of using both this and self:
.attr('class', (d, i, elem) => (this.highlightA && elem.dataset.a) ? 'highlight' : 'normal');
To be clear, I’m not proposing that the context be changed to something else, only that it be possible to get the relevant DOM element without it.
Regarding backwards compatibility, adding an additional argument shouldn’t break anyone’s code, unless they’re for some reason relying on arguments
being a particular length (though if my assumption is mistaken and such a change would indeed be a breaking one, it should probably be left until version 4).
Issue Analytics
- State:
- Created 9 years ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
Related: ES6’s fat arrow syntax uses a lexical binding for
this
. In other words, you cannot access thethis
context that D3 passes to callbacks if you’re using the fat arrow syntax. The solution: don’t use the fat arrow syntax, or alternatively, we may need to consider something like the suggestion above for version 4.0.I’ve standardized d3-selection and d3-transition on the current datum
d
, the group indexi
, and the group nodes array. This is intended to mimic array methods such as array.forEach. Thethis
is the current element.