Reputation: 32803
This might be answered in the documentation but I haven't been able to work it out.
Basically I have some standard d3.js
code like this:
group.selectAll('rect')
.data(data)
.enter().append('svg:rect')
.style('fill', colour)
.on('mouseover', function(d, i) {
chart.currentHoverItem = d
})
.on('mouseout', function(d, i) {
chart.currentHoverItem = null
})
I have a few of these identical lines in different methods throughout my code. Ideally I would like to do this:
var addEvents() {
this.on('mouseover', function(d, i) { ... })
this.on('mouseout', function(d, i) { ... })
}
group.selectAll('rect')
.data(data)
.enter().append('svg:rect')
.apply(addEvents)
What's the nicest solution to DRY up this code?
Upvotes: 0
Views: 954
Reputation: 27813
You might be looking for selection.call, try this:
function addEvents(selection) {
selection.on(...);
selection.on(...);
}
group.selectAll('rect')
.data(data)
.enter()
.append('svg:rect')
.call(addEvents);
Upvotes: 3