简体   繁体   中英

Typescript this keyword not working in a jquery event handler

My typescript code.

class something {
    createSomething(): JQuery {
        let result = $('<div>');
        $('<input>').on('change paste keyup', () => {
            this.myProperty = $(this).val;
            this.change();
        }).appendTo(result);
        return result;
    }
    myProperty: string;
    change() {
        alert('yeah');
    } }

In the handle function-> this and $(this) can't exist in same time.

How can I resolve the problem?

Maybe do a more classic javascript way could solve it, together with function instead of arrow-function.

    var that = this;
    $('<input>').on('change paste keyup', function() {
                that.myProperty = $(this).val;
                that.change();
            }).appendTo(result);

This may help

createSomething(): JQuery {
    var self = this;
    let result = $('<div>');
    $('<input>').on('change paste keyup', () => {
        self.myProperty = $(this).val;
        self.change();
    }).appendTo(result);
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM