When using callbacks in Typescript you would (most of the time) want to invoke object reference methods instead of static methods.
To do this you would need to make use of the "this" keyword inside the callback, but you need to define the callback in a certain way otherwise "this" refers to the callback itself.
The correct way to define the callback method is:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class callbackSample { | |
constructor (){ | |
} | |
doSomethingElse() | |
{ | |
alert('invoked from callback'); | |
} | |
// Define the callback method signature and the implementation | |
public someCallbackMethod: () => void = () => { | |
this.doSomethingElse(); | |
} | |
} |
If you are expecting a JSON result in the callback you can define the callback to use parameters like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class callbackSampleParams { | |
constructor (){ | |
} | |
doSomethingElse(data) | |
{ | |
alert(data); | |
} | |
// Define the callback method signature and the implementation to include params | |
public someCallbackMethod: (data, status, jqXHR) => void = (data, status, jqXHR) => { | |
this.doSomethingElse(data); | |
} | |
} |
Comments
Post a Comment