In my Angular2 component, I am facing an issue with using vis.js
(or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of these events.
For instance, when trying to reference this.visData
within the event handler, it returns as undefined
:
export class GraphContainerComponent implements OnInit {
private visData: {};
private options: {} = {};
private network: any;
@ViewChild('graphContainer') graphContainer;
ngOnInit() {
// initializes this.visData
// this.visData = { nodes, edges }
this.makeGraph();
}
makeGraph() {
// Creating and displaying the graph works without issues
this.network = new vis.Network(this.graphContainer.nativeElement, this.visData, this.options);
// Click event
this.network.on("selectNode", function (params) {
console.log(this.visData); // outputs "undefined"
}
$('a').on('click', function() {
console.log(this.visData); // also returns "undefined"
});
}
}
I recognize that this behavior is expected, and despite knowing that combining Angular2 with jQuery or similar DOM-manipulation libraries is not recommended, sometimes it becomes necessary.
What would be the most effective approach to retain access to my component's properties within these events?
It’s worth noting that there are multiple instances of these components on the page, ruling out the option of using global storage for maintaining references.