Knockoutjs click binding in foreach binding

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.

+7
source share
1 answer

You made me for a second!

You are correct, $parent should be necessary. Your error did not define self in your view model. After that, $parent required in the removeButton file, as well as a masterData binding.

Here is a working fiddle: http://jsfiddle.net/FpSWb/

+8
source

All Articles