Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs click binding within foreach binding

EDIT: Problem was not related to the binding but to a simple JavaScript mistake.

I have a question concerning a click binding within a foreach binding. I have a list with items showing a drop down box to select a value from the master data. Items can be added and removed from that list. The button to remove items is nested in the foreach binding. Therefore I expected that I should bind it with $parent>

<button data-bind="click: $parent.removeNumber">-</button>

That 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 have created a fiddle (with the not working version): http://jsfiddle.net/delixfe/NWWH8/

Thanks for your help.

like image 668
delixfe Avatar asked Jun 05 '12 20:06

delixfe


1 Answers

You had me for a second!

You are correct, $parent should be required. Your mistake was not defining self in your viewmodel. After doing that, $parent was required on the removeButton, as well as the masterData binding.

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

like image 179
Kyeotic Avatar answered Sep 25 '22 17:09

Kyeotic