简体   繁体   English

从jQuery或其他事件访问组件属性

[英]Accessing component properties from jQuery or other events

I'm trying to use vis.js (or jQuery) click events in an Angular2 component. 我正在尝试在Angular2组件中使用vis.js (或jQuery)click事件。 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: 例如,在事件内undefined this.visData

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. 我知道为什么这是正常行为,并且我知道不建议将Angular2和jQuery或其他一些DOM操纵库混合使用 ,但是有时候这就是您所需要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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