1

New to typescript, trying to figure out why this doesn't work:

I have the following class definition:

class SliderRange {

    updateSliderText(lowId: JQuery, highId: JQuery) {
        //do some updates
    }

    constructor(public uiId: string, lowDisplay: JQuery, highDisplay: JQuery) {
        //register the events that tie ui to the set methods here.
        this.primaryUi().on("input", function () {
            this.updateSliderText(lowDisplay, highDisplay);
        });

        this.secondaryUi().on("input", function () {
            this.updateSliderText(lowDisplay, highDisplay);
        }); 
    }

    private primaryUi() : JQuery {
        return $(`.original#${this.uiId}`);
    }
    private secondaryUi(): JQuery {
        return $(`.ghost#${this.uiId}`);
    }
}

The events are being fired correctly, but when they are fired, the browser complains that this.updateSliderText is not a function. Looking in the browser, this isn't being replaced by Typescript, and is instead referencing the JQuery object (primaryUi or secondaryUi). Yet IntelliSense correctly navigates to the proper updateSliderText function, which makes me believe that it should compile into javascript that correctly references that function.

How do I reference a function belonging to the class in the jquery event handlers?

Thank you.

2
  • If you don't use this, only use updateSliderText(lowDisplay, highDisplay), what is happened? Commented Feb 17, 2017 at 0:19
  • @TonyDong TS2304 Cannot find name 'updateSliderText' ts compilation error. Commented Feb 17, 2017 at 0:21

1 Answer 1

5

The this context where you are calling your this.updateSliderText is wrong.

You need an arrow function (they were invented exactly for this reason) or do it the old style, by binding it:

this.primaryUi().on("input", () => { // Yay, cool arrow functions.
    this.updateSliderText(lowDisplay, highDisplay);
});

this.primaryUi().on("input", (function() {
    this.updateSliderText(lowDisplay, highDisplay);
}).bind(this)); // yay...? old-bind-style

The cool and TypeScript method is the arrow one.

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

2 Comments

Cool, that's exactly what I'm looking for! Do you have a link or a name that I can use to google this functionality of the arrow?
Yeah, that's their name. Arrow functions: basarat.gitbooks.io/typescript/content/docs/…

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.