Juicy Juicy - 2 months ago 8
TypeScript Question

Accessing component properties from jQuery or other events

I'm trying to use

vis.js
(or jQuery) click events in an Angular2 component. I have my graph displaying just fine, and I can successfully catch click events.

However, within the context of click events, I loose my references to my component's properties. For example,
this.visData
is
undefined
from within the event:

export class GraphContainerComponent implements OnInit {
private visData: {};
private options: {} = {};
private network: any;
@ViewChild('graphContainer') graphContainer;

ngOnInit() {
// populates this.visData
// this.visData = { nodes, edges }
this.makeGraph();
}

makeGraph() {
// no problem creating and displaying my graph, everything works
this.network = new vis.Network(this.graphContainer.nativeElement, this.visData, this.options);

// click event
this.network.on("selectNode", function (params) {
console.log(this.visData); // logs "undefined"
}

$('a').on('click', function() {
console.log(this.visData); // "undefined" as well
});
}
}


I understand why this is normal behavior, and I know mixing Angular2 and jQuery or some other DOM-manipulating library is not recommended practice, but sometimes it's all you got.

What's the best way to maintain a reference to my component's properties from within these events?

Crucially, there are dozens of these components on my page, so I don't think some kind of global storage is the way to go.

Answer

try to use arrow function (()=>) as shown below,

this.network.on("selectNode", (params)=> {  //<----this should work.
        console.log(this.visData); // logs "undefined"
    }

$('a').on('click', ()=> {                   //<----this should work.
            console.log(this.visData); // "undefined" as well
});