在eacheach绑定中的knockoutjs单击绑定 [英] knockoutjs click binding within foreach binding
问题描述
问题与绑定无关,而与简单的JavaScript错误有关.
我有一个关于foreach绑定内的单击绑定的问题. 我有一个列表,其中包含显示下拉框的项目,以便从主数据中选择一个值.可以在该列表中添加和删除项目. 删除项目的按钮嵌套在foreach绑定中.因此,我希望我应该将其与$ parent>
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>
我不明白为什么.
代码:
<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);
我创建了一个小提琴(使用不起作用的版本): http://jsfiddle.net/delixfe/NWWH8/
I have created a fiddle (with the not working version): http://jsfiddle.net/delixfe/NWWH8/
感谢您的帮助.
推荐答案
您让我有一秒钟!
您是正确的,应该输入$parent
.您的错误是没有在视图模型中定义self
.之后,removeButton和masterData
绑定都需要$parent
.
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.
这是一个有效的小提琴: http://jsfiddle.net/FpSWb/
Here is a working fiddle: http://jsfiddle.net/FpSWb/
这篇关于在eacheach绑定中的knockoutjs单击绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!