I am nesting a lot of elements inside of a g element like so:
<g>
<rect></rect>
<text></text>
...
</g>
However, there are some rects that I want to be able to have drag events of their own. The problem is that when you put stuff inside of a g tag, its size expands to contain those tags. So even though I can assign events there is no way they can be triggered because the g tag's event is somehow more important even though the rect is on top of it.
Is there some sort of workaround that you guys know of?
EDIT: Here's a simple complete case in its entirety. A rect and a circle inside a g. The g is draggable and the circle should be draggable too but is not.
var gDragBehav = d3.behavior.drag()
.on('drag', gDragDrag)
function gDragDrag(d,i) {
d.x += d3.event.dx;
d.y += d3.event.dy;
d3.select(this)
.attr('x', d.x)
.attr('y', d.y)
.attr("transform", "translate(" + d.x + "," + d.y + ")");
}
var circleDragBehav = d3.behavior.drag()
.on('drag', circleDragDrag);
function circleDragDrag(d,i) {
console.log('dragging a circle')
d.cx += d3.event.dx;
d.cy += d3.event.dy;
d3.select(this)
.attr('cx', d.cx)
.attr('cy', d.cy)
}
var svg = d3.select('body').append('svg')
var g = svg.selectAll('g').data([{x: 10, y:10}])
.enter().append('g').call( gDragBehav )
g.append( 'rect' ).attr('width', 100 ).attr('height', 100 )
g.selectAll( 'circle' ).data([{cx: 0, cy:0}])
.enter().append( 'circle' )
.attr('cx', function(d) { return d.cx } ).attr('cy', function(d) { return d.cy } )
.attr('r', 40 )
.call( circleDragBehav )
EDIT: Here's some of the code
var group = this.d3svg.selectAll('g' + '.' + this.className)
.attr('x', this.drawFuncs['x'] )
.attr('y', this.drawFuncs['y'] )
.attr("transform", this.drawFuncs['translate'] )
.attr('class', this.className )
.call(gDragBehav)
.on( 'click', blockClickMenu )
ports = ['AtomicPort']
for ( port in ports ) {
drawPort.call( this, group, ports[port] )
}
function drawPort( d3svg, portName, redraw ) {
d3svg.selectAll('rect.' + portName)
.data( function(d) { return d.ports[ portName ] } )
.enter().append('rect')
.attr('x', this.drawFuncs['x'] )
.attr('y', this.drawFuncs['y'] )
.attr('width', this.drawFuncs['width'] )
.attr('height', this.drawFuncs['height'] )
.attr('class', portName )
.call(portDragBehav)
var portDragBehav = d3.behavior.drag()
.on('drag', portDragDrag);
function portDragDrag(d,i) {
d.x += d3.event.dx;
d.y += d3.event.dy;
d3.select(this)
.attr('x', d.x)
.attr('y', d.y)
d3.event.stopPropagation();
}
var gDragBehav = d3.behavior.drag()
.on('dragstart', gDragStart)
function gDragDrag(d,i) {
d.x += d3.event.dx;
d.y += d3.event.dy;
d3.select(this)
.attr('x', d.x)
.attr('y', d.y)
.attr("transform", "translate(" + d.x + "," + d.y + ")");
d3.event.stopPropagation(); //Uncaught TypeError: Object #<Object> has no method 'stopPropagation'
}
See Question&Answers more detail:
os