I have this very simple test view
<button data-bind="click: add">Add</button>
<table data-bind="foreach: items">
<tr>
<td data-bind="text: name"></td>
<td><button data-bind="click: $root.remove">Remove</button></td>
<tr>
</table>
Fiddle: http://jsfiddle.net/6PP5m/
The problem is that the context of this in the remove method is the child view model that fired the click event
I havent found a solution that I like, you can add a self variable in the contructor and use that instead of "this", but its more clean code and OO to use the "this" keyword
Fiddle: http://jsfiddle.net/Qn2CM/
You can also create a proxy function delegate but its still not very clean code
Fiddle: http://jsfiddle.net/gYhMr/
What I would like is to tell ko somehow to set the context of this to the correct correct scope ($root in this case) is it possible?
The click/event bindings run in the context of the current data as you have found.
There are a few options to ensure that your function runs with the correct context:
this
to a variable likeself
and use it in your handler (as you have mentioned)$.proxy
or.bind
in your view model to ensure thatthis
is correct (as you have mentioned)data-bind="click: $root.remove.bind($root)"
data-bind="click: function() { $root.remove($data); }"