所有`transition`完成后如何调用`callback`函数?

时间:2015-05-24 05:26:05

标签: javascript jquery d3.js

我希望在callback结束后拨打transition。但我没有。来自每个transition端的回调时间。如何结合所有这些并在结束时回电?

这是我的代码:

var fadeHandler = function() {
  var myCallback = function() {
    $.event.trigger('showMenu');
    //this is called 6 times
    // how to get single time call back after completing all 6 transitions?
  }

  d3.selectAll('.subAppGroup .subAppPath, .subAppGroup .subAppGroupDetail') //parent group 6 no.s
    .transition()
    .delay(function(d, i) {
      return i * 500;
    })
    .duration(500)
    .style('opacity', 1)
    .each("end", myCallback); //this is called 6 times

}
fadeHandler();

1 个答案:

答案 0 :(得分:2)

我不确定这是否是解决问题的最佳方法,但它肯定有效。

var fadeHandler = function () {
    var items = d3.selectAll('.subAppGroup .subAppPath, .subAppGroup .subAppGroupDetail'),
        todo = items.size();
    
    items
    .transition()
    .delay(function (d, i) {
        return i * 500;
    })
    .duration(500)
    .style('opacity', 1)
    .each("end", function () {
        todo--;
        if (todo === 0) {
            // $.event.trigger('showMenu');
            $("#allDone").fadeIn();
        }
    });
};

fadeHandler();
.subAppGroup * {
    float: left;
    width: 50px;
    height: 50px;
    opacity: 0.2;
    margin: 4px;
}
.subAppPath {
    background-color: red;
}
.subAppGroupDetail {
    background-color: blue;
}
#allDone {
    display: none;
    clear: both;
    margin: 4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<div class="subAppGroup">
    <div class="subAppPath"></div>
    <div class="subAppGroupDetail"></div>
    <div class="subAppPath"></div>
    <div class="subAppGroupDetail"></div>
    <div class="subAppPath"></div>
    <div class="subAppGroupDetail"></div>
</div>
<div id="allDone">All done!</div>