简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM