简体   繁体   中英

D3: change data based on svg element manipulation

I'm new to [d3.js][1], so my question may be stupid.

I divided my svg into regions, and I appended circles for the user to drag around. Every region has an id, and every circle has the id of the region in which it was created.

What I need is to update the linked to the circle in the drop event. The other way around is quite easy, since when you change the data, the update() event does all the work. But is there a way for the svg element to change the data?

:

Some of the code. I edited so it is cleaner and more direct. The circles call the drag object and everything works, but the TODO section needs to be... hum... done:

var drag;
function configDrag () {
    drag = d3.behavior.drag();
    drag.on("dragstart", function() {
            d3.event.sourceEvent.stopPropagation();
        })
        .origin(function(d){
            return d;
        })
        .on("dragstart", draggrab)
        .on("drag", dragmove)
        .on("dragend", dragdrop);
}

function dragdrop(d){
    reg = regionOf(d.x, d.y);    // null if in undefined region
    if(reg){
        d3.select(this)
            .attr("cy", parseInt(reg.y1 + reg.y2) / 2);

        var regionId = getRegionId(d.x, d.y);
        // TODO update data.tsv with regionId
        }
    }
}

When you bind data to a selection using selection.data(values) , values is always an array and normally an array of object elements. Those elements, or references to them, are bound to the DOM elements and can be retrieved using selection.datum() . They are also the d argument that is normally the first argument passed callbacks by the various d3 operator methods. Because they are objects, when you change the value of their members, you are changing the values of the members of the associated element, in the original values array that was bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM