Search code examples
javascriptgraph-theorydijkstracytoscape

cytoscape js dijkstra method throwing TypeError on the callback


I get the following error when I run the below code:

TypeError: Cannot read property 'data' of undefined

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);

This is almost exactly the same code as described in cytoscape's documentation so I'm not sure where I went wrong. When I run dijkstra without the callback I receive no errors and I'm even able to perform pathTo() and distanceTo() on the returned result. FIDDLE


Solution

  • Arrow functions do not have a this binding. But the edge is passed to that weight function and it might be even better to read if you change your code to:

    const dijkstra = testGraph.elements().dijkstra('#a', (edge) => {
      return edge.data('weight');
    }, false);
    
    var distanceToC = dijkstra.distanceTo(testGraph.$('#c')); // 3
    

    Fiddle