TypeScript and Knockout binding to 'this' issue - lambda function needed?

后端 未结 8 1613
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 18:28

I\'ve been creating a htmlHelper function using TypeScript and KnockoutJS to edit a list of emails.

The list of emails is a Knockout ObservableArray called e

相关标签:
8条回答
  • 2020-12-04 18:56

    I was inspired by the bind answer and came up with this, I think it a little easier to read.

    <a href="#" data-bind="click: function () {$parent.deleteItem()}">Delete</a>

    Wrap the method in a lambda/anonymous function. Don't forget the ().

    0 讨论(0)
  • 2020-12-04 18:58

    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);
        }        
    }
    
    0 讨论(0)
提交回复
热议问题