Trying to use the new cleaner event handling in Knockout 2 along with the new control flow bindings I’m working on implementing a simple dynamic list, adding and removing strings. So my markup roughly looks like this:
<div data-bind="foreach:myList">
<input data-bind="value: $data" />
<button data-bind="click:$parent.removeFromList">X</button>
</div>
and my viewmodel has a matching remove function which immitates a sample from Steve Sanderson.
removeFromList: function(item) {
this.myList.remove(item);
}
Now I would expect ‘this’ to refer to the viewmodel and item to refer to the array member being removed (since event handlers now receive the current model value as their first parameter). However, ‘this’ also seems to refer to the string being removed. Therefore when I click remove I get:
this.myList is undefined
I’ve created a JSFiddle at http://jsfiddle.net/davidc/rFd7H/ which illustrates my problem. How should I be removing items from the list?
There are many ways that you can ensure that your handler has the correct value for “this”.
Build your view model in a function and use
bindagainst the currentthisSample: http://jsfiddle.net/rniemeyer/rFd7H/4/. Or don’t build your view model in a function and usebindlike: http://jsfiddle.net/rniemeyer/rFd7H/10/Build your view model in a function and keep a variable with the correct value of
thisand use it in your handler. Sample: http://jsfiddle.net/rniemeyer/rFd7H/5/Bind to the correct context within your binding like:
data-bind="click: $parent.removeFromList.bind($parent)"Sample: http://jsfiddle.net/rniemeyer/rFd7H/8/Call it as an anonymous function off of the
$parentobject like:data-bind="function() { $parent.removeFromList($data); }"Generally, not recommended, as it makes the markup ugly/verbose. Sample: http://jsfiddle.net/rniemeyer/rFd7H/9/