9

我正在将我的 AS3 代码库转换为 TypeScript 并遇到此错误:

AS3 代码:

private function loadDataXml(assetsXml : String) : void {
    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, handleDataLoaded);
    loader.load(new URLRequest(assetsXml));
}

private function handleDataLoaded(event : Event) : void {
    var xml_data : XML = new XML(event.target.data);
    parseData(xml_data);
    .........
}

private function parseData(xml_data : XML) : void {
    ......
}

打字稿代码

private loadDataXml(assetsXml : string) {
    var xmlRequest:XMLHttpRequest = new XMLHttpRequest();
    xmlRequest.addEventListener("load",this.handleDataLoaded, false);
    xmlRequest.open("GET", assetsXml, false);
    xmlRequest.setRequestHeader("Content-Type", "text/xml");
    xmlRequest.send(null);
}

private handleDataLoaded(evt:Event) {
    var xmlDoc:Document = (<XMLHttpRequest> evt.target).responseXML;
    this.parseXMLData(xmlDoc);
    ......
}

private parseData(xmlDoc:Document):void {
    ......
}

由于这条线 xmlRequest.addEventListener ,我得到了这个错误“Uncaught TypeError: Object # has no method 'parseData'”.....

我尝试过使用箭头功能但仍然无法修复它(而且我认为我没有正确使用它)

4

2 回答 2

20

When you need to pass functions around use the new lambda syntax for member variables (introduced in TypeScript 0.9.1):

private loadDataXml(assetsXml : string) {
    var xmlRequest:XMLHttpRequest = new XMLHttpRequest();
    // you are passing a member function Use lambda to define this function: 
    xmlRequest.addEventListener("load",this.handleDataLoaded, false);
    xmlRequest.open("GET", assetsXml, false);
    xmlRequest.setRequestHeader("Content-Type", "text/xml");
    xmlRequest.send(null);
}

private handleDataLoaded = (evt:Event) => { // Since you want to pass this around  
    var xmlDoc:Document = (<XMLHttpRequest> evt.target).responseXML;
    this.parseXMLData(xmlDoc);  // you will get the correct this here 
    ......
}

private parseData(xmlDoc:Document):void {
    ......
}
于 2013-08-24T23:30:35.520 回答
2

尝试绑定到范围

xmlRequest.addEventListener("load",this.handleDataLoaded.bind(this), false);
于 2016-07-13T14:47:18.533 回答