所以我在网上发现了这段代码,它计算了d3图中节点上dijkstra的最短路径算法。问题是d3.rebind已被删除,我还没有找到一种方法来修复这段代码以使其工作。有什么建议?另外我知道这段代码不是我的,这就是为什么我在理解如何更改代码方面遇到一些问题。 感谢
d3.dijkstra = function () {
var dijkstra = {};
var nodes;
var edges;
var source;
var dispatch = d3.dispatch("start", "tick", "step", "end");
dijkstra.run = function (src) {
source = src;
var unvisited = [];
nodes.forEach(function (d) {
if (d != src) {
d.distance = Infinity;
unvisited.push(d);
d.visited = false;
}
});
var current = src;
current.distance = 0;
function tick() {
current.visited = true;
current.links.forEach(function(link) {
var tar = link.target;
if (!tar.visited) {
var dist = current.distance + link.value;
tar.distance = Math.min(dist, tar.distance);
}
});
if (unvisited.length == 0 || current.distance == Infinity) {
dispatch.end()
return true;
}
unvisited.sort(function(a, b) {
return b.distance - a.distance
});
current = unvisited.pop()
dispatch.tick();
return false;
}
d3.timer(tick);
};
dijkstra.nodes = function (_) {
if (!arguments.length)
return nodes;
else {
nodes = _;
return dijkstra;
}
};
dijkstra.edges = function (_) {
if (!arguments.length)
return edges;
else {
edges = _;
return dijkstra;
}
};
dijkstra.source = function(_) {
if (!arguments.length)
return source;
else {
source = _;
return dijkstra;
}
};
dispatch.on("start.code", dijkstra.run);
return d3.rebind(dijkstra, dispatch, "on", "end", "start", "tick");
};
答案 0 :(得分:6)
如您所知,D3 {4}中删除了d3.rebind()
。 According to Mike Bostock(D3创作者):
如果您需要此类功能,可以从v3中复制实现。
这是v3的source code:
// 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;
};
}
正如您所见,它的使用非常简单。
所以,假设我们有这个代码,运行D3 v3:
var foo = {
hello: function() {
console.log("hello");
return this;
},
world: function() {
console.log("world");
return this;
}
};
var bar = {};
d3.rebind(bar, foo, "hello", "world")
bar.hello().world()
&#13;
<script src="https://d3js.org/d3.v3.min.js"></script>
&#13;
如果在没有D3 v3的情况下使用rebind
使用相同的代码,则只需复制原始函数即可。
就是这样:
var foo = {
hello: function() {
console.log("hello");
return this;
},
world: function() {
console.log("world");
return this;
}
};
var bar = {};
rebind(bar, foo, "hello", "world");
bar.hello().world()
function rebind(target, source) {
var i = 1,
n = arguments.length,
method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
function d3_rebind(target, source, method) {
return function() {
var value = method.apply(source, arguments);
return value === source ? target : value;
};
}
&#13;