TypeScript - 在事件侦听器中保留范围

时间:2013-08-24 21:45:11

标签: scope typescript

我正在将我的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 {
    ......
}

TypeScript代码

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 {
    ......
}

我收到此错误“未捕获TypeError:对象#没有方法'parseData'”因为这行xmlRequest.addEventListener .....

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

2 个答案:

答案 0 :(得分:18)

当你需要传递函数时,使用成员变量的新lambda语法(在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 {
    ......
}

答案 1 :(得分:2)

尝试绑定到范围

xmlRequest.addEventListener("load",this.handleDataLoaded.bind(this), false);