TypeScript - save scope in event listener

I convert my AS3 database to TypeScript and run this error:

AS3 Code:

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 code

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

and I get this error "Uncaught TypeError: Object # does not have a method" parseData "because of this line xmlRequest.addEventListener .....

I tried using the arrow function, but still could not fix it (and I don’t think I am using it correctly)

+7
scope typescript
source share
2 answers

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 { ...... } 
+16
source share

Try snap to area

 xmlRequest.addEventListener("load",this.handleDataLoaded.bind(this), false); 
+2
source share

All Articles