Calling from an internal callback using typescript
I'm having a hard time calling a method from another method in the same class in TypeScript. I want to call a method routeTheRequest
from onRequest
within a method , but I cannot get it to work.
index.ts
import server = require("./server");
new server.MyServer();
server.ts
import http = require("http");
export class MyServer{
public constructor(){
http.createServer(this.onRequest).listen(8888);
console.log("Server has started.");
}
private onRequest(request: http.ServerRequest, response: http.ServerResponse){
var path = request.url;
this.routeTheRequest(path); // *** how do i call routeTheRequest ?? ***
response.writeHead(200, { "Content-Type": "text/plain" });
response.end();
}
private routeTheRequest(urlString: string): void{
console.log("user requested : " + urlString);
}
}
Usage this.routeTheRequest
doesn't work, this
loses scope and refers to the object http.Server
being returned createServer
. I've tried almost all different ways to call this
from these pages ...
How to preserve lexical scope in TypeScript with callback function
TypeScript "his" error when called in jquery callback
A non-jQuery solution would be preferred. Thanks to
source to share
You can fix this by writing a method onRequest
like this. Note that you shouldn't write all of these methods as it costs some performance (it creates a new function for each instance instead of putting it into the prototype), but it doesn't really matter in this case.
class MyServer {
private onRequest = (request: http.ServerRequest, response: http.ServerResponse) => {
var path = request.url;
this.routeTheRequest(path); // *** how do i call routeTheRequest ?? ***
response.writeHead(200, { "Content-Type": "text/plain" });
response.end();
}
}
Note the lambda on the function.
Another way:
http.createServer(this.onRequest.bind(this)).listen(8888);
edit: I talked about it being expensive, but the impact isn't that great, but what I really meant was that I didn't write every method this way (only to those who need to capture this
and call by passing a method to another functions).
source to share