cytoscape.jscytoscapecytoscape-web

Call a method on click on a node on cytoscape graph


I am trying to call a method by passing in the id of the node but it keeps saying that method is not a function.

Here is the stackblitz link: https://stackblitz.com/edit/cytoscape-call-method?file=src/app/app.component.ts

You can click on any node and see the console error. It says this.showId is not a function.

Some code

 this.cy.on('click', 'node', function(evt) {
      console.log('clicked ' + this.id());
      this.showId(this.id());
    });

I have tried using tap as well but it still gives the same error.


Solution

  • Hm I think I see what you mean. It's about scopes in JS. Try below

    this.cy.on('click', 'node', (evt) => {
      console.log('clicked ' + this.id());
      this.showId(this.id());
    });
    

    or below

    this.cy.on('click', 'node', function (evt) {
      console.log('clicked ' + this.id());
      this.showId(this.id());
    }.bind(this));
    

    Both are actually the same