javascript 在foreach绑定中knockoutjs点击绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10904070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:25:43  来源:igfitidea点击:

knockoutjs click binding within foreach binding

javascriptknockout.js

提问by delixfe

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

编辑:问题与绑定无关,而是与一个简单的 JavaScript 错误有关。

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>

我有一个关于 foreach 绑定中的点击绑定的问题。我有一个包含项目的列表,其中显示了一个下拉框,用于从主数据中选择一个值。可以在该列表中添加和删除项目。删除项目的按钮嵌套在 foreach 绑定中。因此我希望我应该将它与 $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/

我创建了一个小提琴(不工作的版本):http: //jsfiddle.net/delixfe/NWWH8/

Thanks for your help.

谢谢你的帮助。

回答by Kyeotic

You had me for a second!

你有我一秒钟!

You are correct, $parentshould be required. Your mistake was not defining selfin your viewmodel. After doing that, $parentwas required on the removeButton, as well as the masterDatabinding.

你是对的,$parent应该是需要的。你的错误没有self在你的视图模型中定义。这样做之后,$parent需要在 removeButton 以及masterData绑定上。

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

这是一个工作小提琴:http: //jsfiddle.net/FpSWb/