2

I'm currently working with the AlpacaJS library within my typescript project. This JavaScript/JQuery library is included in my Typescript class and wants me to pass some options in a json style object like so:

this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(this.getValue());
                }
            }
        }
    }
};

Passing this object i say: add a change event to the field "id" within the form which alpaca generates. Using "this" within that function gives me the "this" of the library, and NOT the typescript class "this".

The problem: What if i like to call a method or variable within my Typescript class? I would have to use "this", but "this" is binded to the alpaca/javascript this. I can't change it to (event) => { ... } or { ...}.bind(this) because that way i CAN access the typescript "this", but i CAN'T access the alpaca/javascript this, i need both of them....

1 Answer 1

4

i CAN'T access the alpaca/javascript this, i need both of them

Use the standard javascript trick of capturing this before creating the function:

let _self = this;
this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(_self.getValue());  // the class instance
                    console.log(this); // the lib version 
                }
            }
        }
    }
};

This tip is documented here as well : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

Sign up to request clarification or add additional context in comments.

7 Comments

Using self withtin typescript return an object of type Window ? It doesn't contain my Typescript methods/variables
I missed the line let _self = this; -.- I'm sorry. Looks like this is working! Going to test it out
Between, just wondering. Why CAN i access a let within this block scope but can't i access the other typescript variables/functions?
can't i access the other typescript variables/functions? : You can. Not sure what you mean
So why can't i, but can i access the _self There is only one thing that the effectively a variable this can be bound to. If you use a fat arrow it is bound to the lexical scope (in your case the class instance). Without it it is a choice on who calls the function (the library in this case). Since you want two things you need to use two variables. In your case one is this (from the lib) and the other is _self (bound to the class instance)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.