2016-12-16 24 views
1

我正在做一個名爲VisJS的圖形庫(http://visjs.org/)的適用性測試。我已經將它與Angular2集成在一起,但是當網絡元素被點擊時,我想調用一個angular2組件函數。這裏是我的組件產生一個基本的網絡圖:從VisJS事件調用Angular2組件功能

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

,而不是

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

我想這樣做

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

但這混合angular2與jQuery方法...我如何去做這件事?

回答

0

我改成了這樣:

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

我認爲這個問題是,當該方法是這樣的:

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

的「本」關鍵字是作用範圍內的功能和我不能引用任何組件memebers。