我尝试恢复以前版本的 D3 中为“node.on”方法呈现的双击事件。我需要将它与 d3.forceSimulation 一起使用。
我发现双击事件的替代片段在旧版本的d3上运行良好。它还使用旧的 d3.rebind 方法,该方法已从当前 d3 中删除,并且也具有替代方法。我试图合并这两个片段,但失败并出现错误“无法读取未定义的属性”应用“。
这是合并后的代码:
<div id='map'></div>
<script>
function clickcancel() {
// Copies a variable number of methods from source to target.
d3.rebind = function(target, source) {
var i = 1, n = arguments.length, method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
// Method is assumed to be a standard D3 getter-setter:
// If passed with no arguments, gets the value.
// If passed with arguments, sets the value and returns the target.
function d3_rebind(target, source, method) {
return function() {
var value = method.apply(source, arguments);
return value === source ? target : value;
};
}
// we want to a distinguish single/double click
// details http://bl.ocks.org/couchand/6394506
var event = d3.dispatch('click', 'dblclick');
function cc(selection) {
var down, tolerance = 5, last, wait = null, args;
// euclidean distance
function dist(a, b) {
return Math.sqrt(Math.pow(a[0] - b[0], 2), Math.pow(a[1] - b[1], 2));
}
selection.on('mousedown', function() {
down = d3.mouse(document.body);
last = +new Date();
args = arguments;
});
selection.on('mouseup', function() {
if (dist(down, d3.mouse(document.body)) > tolerance) {
return;
} else {
if (wait) {
window.clearTimeout(wait);
wait = null;
event.dblclick.apply(this, args);
} else {
wait = window.setTimeout((function() {
return function() {
event.click.apply(this, args);
wait = null;
};
})(), 300);
}
}
});
};
return d3.rebind(cc, event, 'on');
}
var cc = clickcancel();
d3.select('#map').call(cc);
cc.on('click', function(d, index) {
d3.select('#map').text(d3.select('#map').text() + 'click, ');
});
cc.on('dblclick', function(d, index) {
d3.select('#map').text(d3.select('#map').text() + 'dblclick, ');
});