TypeScript and Knockout binding to ‘this’ issue – lambda function needed?

You can get correct closure for ‘this’ by declaring method body inside class constructor

class VM {
    public deleteItem: (emailToDelete: string) => void;

    constructor() {
        this.deleteItem = (emailToDelete: string) => {
            // 'this' will be pointing to 'this' from constructor
            // no matter from where this method will be called
            this.emails.remove(emailToDelete);
        }
    }        
}

UPDATE:

It seems that since Typescript ver 0.9.1 you can achieve the same result by using lambda field initializers:

class VM {
    public deleteItem = (emailToDelete: string) => {
        this.emails.remove(emailToDelete);
    }        
}

Leave a Comment

tech