cytoscape js dijkstra方法在回调上抛出TypeError

时间:2017-10-31 01:03:19

标签: javascript graph-theory dijkstra cytoscape

运行以下代码时出现以下错误:

  

TypeError:无法读取未定义的属性“数据”

const elementsList = [
            {data: {id: 'a'}},
            {data: {id: 'b'}},
            {data: {id: 'c'}},
            {data: {id: 'ab', source: 'a', target: 'b', weight: 4}},
            {data: {id: 'as', source: 'a', target: 'c', weight: 3}}
        ];
        const testGraph = cytoscape({elements: elementsList});
        const dijkstra = testGraph.elements().dijkstra('#a', () => {
            return this.data('weight');
        }, false);

这几乎与cytoscape文档中描述的代码完全相同,所以我不确定我哪里出错了。 当我在没有回调的情况下运行dijkstra时,我没有收到任何错误,我甚至能够对返回的结果执行pathTo()distanceTo()FIDDLE

1 个答案:

答案 0 :(得分:0)

Arrow functions没有此绑定。但边缘被传递给该权重函数,如果将代码更改为:

,则可能更好
const dijkstra = testGraph.elements().dijkstra('#a', (edge) => {
  return edge.data('weight');
}, false);

var distanceToC = dijkstra.distanceTo(testGraph.$('#c')); // 3

Fiddle