I've attempted to write a class in TypeScript that has a method defined which acts as an event handler callback to a jQuery event.
class Editor { textarea: JQuery; constructor(public id: string) { this.textarea = $(id); this.textarea.focusin(onFocusIn); } onFocusIn(e: JQueryEventObject) { var height = this.textarea.css('height'); // <-- This is not good. } }
Within the onFocusIn event handler, TypeScript sees 'this' as being the 'this' of the class. However, jQuery overrides the this reference and sets it to the DOM object associated with the event.
One alternative is to define a lambda within the constructor as the event handler, in which case TypeScript creates a sort of closure with a hidden _this alias.
class Editor { textarea: JQuery; constructor(public id: string) { this.textarea = $(id); this.textarea.focusin((e) => { var height = this.textarea.css('height'); // <-- This is good. }); } }
My question is, is there another way to access the this reference within the method-based event handler using TypeScript, to overcome this jQuery behavior?
In Typescript, Type aliases give a type a new name. They are similar to interfaces in that they can be used to name primitives and any other kinds that you'd have to define by hand otherwise. Aliasing doesn't truly create a new type; instead, it gives that type a new name.
Introduction. One of the most important concepts to grasp in TypeScript is the use of the "this" keyword, which is used in object methods. The "this" keyword always points to the object that is calling a particular method.
A type alias is basically a name for any type. Type aliases can be used to represent not only primitives but also object types, union types, tuples and intersections.
In Typescript, Type assertion is a technique that informs the compiler about the type of a variable. Type assertion is similar to typecasting but it doesn't reconstruct code. You can use type assertion to specify a value's type and tell the compiler not to deduce it.
The scope of this
is preserved when using the arrow function syntax () => { ... }
- here is an example taken from TypeScript For JavaScript Programmers.
var ScopeExample = { text: "Text from outer function", run: function() { setTimeout( () => { alert(this.text); }, 1000); } };
Note that this.text
gives you Text from outer function
because the arrow function syntax preserves the "lexical scope".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With