EDIT: The problem is not with binding, but with a simple JavaScript error.
I have a question about click binding in foreach binding. I have a list with items showing a drop down to select a value from the master data. Items can be added and removed from this list. The button for deleting elements is nested in the foreach binding. So I expected that I should bind it to $ parent>
<button data-bind="click: $parent.removeNumber">-</button>
This does not work. But the following version works:
<button data-bind="click: removeNumber">-</button>
I do not understand why.
The code:
<h2>numbers:</h2> <ul data-bind="foreach: numbers"> <li> <select data-bind="value: id, options: masterData, optionsText: 'caption', optionsValue: 'id'"></select> <br /> value: <span data-bind="text: id"></span> <br /> <button data-bind="click: $parent.removeNumber">-</button> </li> </ul> <button data-bind="click: addNumber">+</button>
function ViewModel() { self.masterData = [{ id: 1, caption: "One"}, { id: 2, caption: "Two"}]; self.numbers = ko.observableArray([{ id: ko.observable(2)}]); self.addNumber = function() { self.numbers.push({ id: ko.observable(2) }); }; self.removeNumber = function(item) { self.numbers.destroy(item); console.log("removed" + item); }; } var viewModel = new ViewModel(); ko.applyBindings(viewModel);â
I created a fiddle (with a non-working version): http://jsfiddle.net/delixfe/NWWH8/
Thank you for your help.
delixfe
source share