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 emails, and I have a link against each item to delete them. This is the HTML fragment:
<ul data-bind="foreach: emails" >
<li>
<a href="#" data-bind="click: $parent.deleteItem">Delete</a>
<span data-bind="text: $data"></span>
</li>
</ul>
The delete link is bound to $parent.deleteItem this is a method in the viewmodel:
// remove item
public deleteItem(emailToDelete: string) {
// remove item from list
this.emails.remove(emailToDelete);
}
This all works until the deleteItem method is executed. The "this" in this method when it is called is the item in the array, and not the view model. Hence this.emails is a null reference and fails.
I know that TypeScript supports the Lambda syntax but I can't find the right way to write this (there few examples out there).
Or is there a different approach I could take?
You might want a polyfill for
Function.bind()
:My final solution is a base class, that rebinds all prototype functions to itself on constructor. Much like Markus Jarderot's solution.
Advantages:
PS:
You still will need the bind polyfill.
I'm using typesript 0.9.5
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 ().
to add my 2 cents, there's also a dirty way, that leverages the variable _this created by the Typescript compiler to keep a reference on this :
Use data-bind something like this:
Assign
this
tothat
as shown belowAlthough I prefer Markus' solution, here's what I have used before to work around this issue:
Note that additional arguments can be passed to the method by adding them after the name of the method: