Search code examples
angularvis.js-network

Calling a custom method from the manipulation at delete node vis.js


I am trying to use vis.js (v4.21.0) with Angular (v4.2.4).

I want to call a custom method before deleting the node, so I added a method to delete node in manipulation, but I am unable to call my custom method from it.

My-component.ts

export class MyComponentComponent implements OnInit {

private graphData: any;
private options: any;

constructor() { }

ngOnInit() {
let nodeList = new Vis.DataSet([
  {id: 1, label: 'Node 1'},
  {id: 2, label: 'Node 2'},
  {id: 3, label: 'Node 3'},
  {id: 4, label: 'Node 4'},
  {id: 5, label: 'Node 5'}
]);

// create an array with edges
let edgeList = new Vis.DataSet([
  {from: 1, to: 3},
  {from: 1, to: 2},
  {from: 2, to: 4},
  {from: 2, to: 5}
]);
this.graphData = {nodes: nodeList, edges: edgeList};

this.options = {
manipulation: {
  enabled: true,
  initiallyActive: false,
  addNode: true,
  addEdge: true,
  editEdge: true,
  deleteNode: function(nodeData,callback) {
    this.deleteNodeFunction(nodeData); // defined below
     `here getting issue ''this'' is not defined.`
  },
  deleteEdge: true,
}
};

let network;

try {
 const container = document.getElementById('test');
  network = new Vis.Network(container, this.graphData, this.options);

}catch (e) {
  console.log(e.message)
}
}

deleteNodeFunction(nodeData){
// do something here 
// may be call some other method.
}

}

Solution

  • Try this:

    deleteNode: function(nodeData,callback) {
      this.deleteNodeFunction(nodeData); // defined below
    }.bind(this),
    

    What's happening is that when Vis.js goes to call your deleteNode() method, it's calling it with its own context, so this is now referring to the network rather than your MyComponentComponent instance. The network has no deleteNodeFunction() method, so nothing happens.

    Calling .bind(this) should prevent the issue. Alternatively, you could use an arrow function, which has automatic binding:

    deleteNode: (nodeData,callback) => {
      this.deleteNodeFunction(nodeData); // defined below
    },