0

I searched all over stackoverflow and found alot of posts, so im pretty sure its duplicate, however i could not find any post that was noob friendly and clear to me, maybe because im pretty new to typescript.

What i am currently working with is typescript classes, and click in Jquery. Normaly this or $(this) works for getting the Jquery item, but then againin TS this is normally reserved for the class:

When i use Jquery the this becomes replaced by the Jquery object.

So i am currently working with:

HTML:

<a data-id="6" class="js-set-crime-option btn btn-primary">Kies</a>

TS:

class Dealers
{
    constructor() {
        $(".js-set-crime-option").click(this.set);
    }

    public set() {
        var a = $(this);
        alert(a.data("id"));

        debugger;
        // i want to call test here
    }

    public test(id: string) {
        alert("helooooooo" + id);
    }

}

how can i call test in this scope?

EDIT: i found this not sure if it is the correct solution though

var me: Dealers;

class Dealers
{
    name:string = "friend";

    constructor() {
        $(".js-set-crime-option").click(this.set);
        me = this;
    }

    public set() {
        var a = $(this);
        me.test(a.data("id"));
    }

    public test(id: string) {
        alert("helooooooo" + id + this.name);
    }

}
1
  • "Normaly this or $(this) works for getting the Jquery item, but then againin TS this is normally reserved for the class" is not true. Furthermore, TypeScript classes are JavaScript classes. Commented Oct 5, 2017 at 5:50

1 Answer 1

1

You should use the fat arrow notation to automatically preserve the correct 'this' but your suggestion should also work although it is safer to save this before attaching the handler .

element.click( () => { this.test(id); } );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.