简体   繁体   中英

Change object attribute following transition D3

I want to give an object an attribute once a transition is finished. I'm simply updating an images position as follows:

tmp.transition().duration(1000)
                    .attr("transform", function(d) {return 'translate(' + 
                    coordinates[d].x +',' + 
                    coordinates[d].y + ')'})

Once it finishes, I want to give the object tmp an attribute "moved" with the value "no". I tried:

tmp.transition().duration(1000)
     .attr("transform", function(d) {return 'translate(' + 
            coordinates[d].x +',' + 
            coordinates[d].y + ')'}).end('moved', 'no')

But without success. Any tips? Thanks,

According to the documentation , you can use .each :

tmp.transition().duration(1000)
 .attr("transform", function(d) {return 'translate(' + 
        coordinates[d].x +',' + 
        coordinates[d].y + ')'}
 ).each('end', function() {
     d3.select(this).attr('moved', 'no');
     // or maybe also this.setAttribute('moved', 'no');
 });

You can tell javascript to wait for a period of time and run code after using window.setTimeout. You simply have to sync both events up by using the same number of milliseconds.

window.setTimeout(function(){
    //Your fake "callback" code here
}, 1000);

In response to @user1066286 (and because I cannot post comments): you shouldn't use setTimout() here! Appart from it being bad practice, you cannot guarantee that the transition will actually be completed when the timeout stops.

From the d3 Transition docs:

Transitions have a four-phase life cycle:

The transition is scheduled. The transition starts. The transition runs. The transition ends.

Each of these four phazes are processed asynchronously, so there's no way to know how long the transition actually takes. It maight be a little slower then the user-defined duration, it might be a little faster.

@Felix Klings answer appears to be deprecated. See https://stackoverflow.com/a/10692220/14095529 (block below is quote from that answer).

// d3 v5
d3.select("#myid").transition().style("opacity","0").on("end", myCallback);

// old way
d3.select("#myid").transition().style("opacity","0").each("end", myCallback);

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