假设您从 foreach 绑定内部调用,我相信您应该使用 $parent 上下文来调用删除函数:
<button data-bind="click: $parent.remove">
<i class="icon-ok"></i>
</button>
这是我通常如何从列表中添加/删除项目的示例小提琴:
http://jsfiddle.net/E53tc/
html
<ul data-bind="foreach: products">
<li>
<span data-bind="text: name"></span>
<button data-bind="click: $parent.remove">Remove</button>
</li>
</ul>
<button data-bind="click: add">Add New </button>
javscript
var product = function (data) {
var self = this;
self.name = ko.observable(data);
}
var vm = function () {
var self = this;
self.remove = function (item) {
self.products.remove(item);
};
self.add = function () {
self.products.push(new product("new product"));
}
self.products = ko.observableArray();
}
var viewModel = new vm();
viewModel.products([ new product("product a"), new product("product b")]);
ko.applyBindings(viewModel);