2016-12-16 4 views
1

Ich mache einige Eignungstests für eine grafische Bibliothek namens VisJS (http://visjs.org/). Ich habe es mit Angular2 integriert, aber ich möchte eine angular2 Komponente Funktion aufrufen, wenn das Netzwerkelement angeklickt wird. Hier ist meine Komponente, die eine grundlegende Netzwerk-Diagramm erzeugt:Invoke Angular2 Komponente Funktion von VisJS Ereignis

import {Component, OnInit, ViewChild, ElementRef} from '@angular/core' 

//reference to visjs library 
declare var vis: any; 

@Component({ 
    selector: 'visjs', 
    templateUrl: './app/visJs/visjs.basic.html' 
}) 

export class VisJsBasicComponent implements OnInit { 

    @ViewChild('network') _element: ElementRef; 

    ngOnInit() { 

     this.createBasicNetwork(); 
    } 

    createBasicNetwork(): void{ 
     // create an array with nodes 
     var nodes = 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 
     var edges = new vis.DataSet([ 
      { from: 3, to: 1 }, 
      { from: 1, to: 2 }, 
      { from: 2, to: 4 }, 
      { from: 2, to: 5 } 
     ]); 

     //create the network 
     var data = { 
      nodes: nodes, 
      edges: edges 
     }; 
     var options = {}; 
     var network = new vis.Network(this._element.nativeElement, data, options); 

     network.on("click", function (params) { 
      window.alert('onclick'); 
     }); 
    } 
} 

statt

network.on("click", function (params) { 
      window.alert('onclick'); 
     }); 

würde Ich mag so etwas wie

network.on("click", function (params) { 
     this.myComponentFunction(params); 
    }); 

tun, aber dies ist das Mischen angular2 mit jquery Methoden ... Wie gehe ich vor?

Antwort

0

Ich änderte es dazu:

var network = new vis.Network(this._element.nativeElement, data, options); 

network.on('click', (params) => { 
    if (params && params.nodes && params.nodes.length === 1) { 
     this.nodeClicked(params); 
    } else { 
     console.log('non node element clicked'); 
    } 
});  
} 

nodeClicked(params: any): void { 
    this._router.navigate(['/Node',params.nodes[0]]); 
} 

ich glaube, das Problem war, dass, wenn das Verfahren so ausgesehen:

function (params) { 
      window.alert('onclick'); 
     } 

die ‚this‘ Schlüsselwort auf die innere Funktion scoped wurde und ich konnte keine Komponentenmitglieder referenzieren.