d3 preventing drag on specific elements

161 Views Asked by At

I am trying to draw few rectangles in d3. I have an array which holds JSON objects of rectangle properties.

var rectObj = {
    id : 'streams',
    x : 10,
    y : 10,
    height : 50,
    width : 100, 
    drag:'true'
};

Some rectangles have draggable='true', while the others have draggable='false'.

I want to draw all the rectangle in a single SVG. They way I do it is,

var rectangles = mainLayout
            .selectAll('rect')
            .data(rectObjects)
            .enter()
            .append('rect');

rectangles
        .attr("x", function (d) { return d.x; })
        .attr("initial-x", function (d) { return d.x; })
        .attr("y", function (d) { return d.y; })
        .attr("initial-y", function (d) { return d.y; })
        .attr("height", function (d) { return d.height; })
        .attr("width", function (d) { return d.width; })
        .attr("fill", function () { return "white"; })
        .attr("stroke", function () { return "black"; })
        .style("stroke-width", function() { return "1 px"; })
        .attr("draggable",function(d){return d.drag;})
        .call(dragStream)
;

On the dragStream, I want to stop the drag function from executing. That is, those rectangle should not do anything on drag.

var dragStream= d3.behavior.drag()
                    .on('dragstart', function(){
                        console.log('drg' + d3.select(this).attr('draggable'));
                        if(d3.select(this).attr('draggable') == 'false'){
                           // what should I do here ? 
                        }
                    })
            .on('drag', move /* this function is defined and works well*/)
            .on('dragend', function(){ // I do some stuff here

   });

What should I do to get the above requirement?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to differentiate in the drag event, not dragstart.

.on('drag', function(d, i) { if(d3.select(this).datum().drag) move.call(this, d, i); }).

And if you use .datum(). then you don't need to write any attributes. When d3 binds data to the selection it is stored on the DOM element, you can access it using .datum(). The value returned by this is a reference to the data array object so you can access the drag property there.