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
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 ().
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);
}
}