未绑定到foreach中的单击动作的函数 [英] Function bound to click action in foreach not being called
问题描述
我无法将click动作绑定到视图模型函数以从数组中删除项目(在foreach
绑定内部)
I'm having trouble binding my click action to the view model function to remove an item from an array (inside a foreach
binding)
我有以下视图模型
var FileGroupViewModel = function () {
var self = this;
self.files = ko.observableArray();
self.removeFile = function (item) {
self.files.remove(item);
}
self.fileUpload = function (data, e) {
var file = e.target.files[0];
self.files.push(file);
};
}
var ViewModel = function () {
var self = this;
self.FileGroup = ko.observableArray();
self.FileGroup1 = new FileGroupViewModel();
self.FileGroup2 = new FileGroupViewModel();
self.FileGroup3 = new FileGroupViewModel();
self.uploadFiles = function () {
alert("Uploading");
}
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
我的视图基本上列出了3个组"按钮,用户可以在其中选择要上传的文件
And my view, which basically lists 3 "groups" of buttons, where a user can select files to upload
除了$parent.removeFile
不会删除文件之外,以下所有内容均按预期工作:
Everything below is working as expected, except $parent.removeFile
isn't removing the file:
<div class="row files">
<h2>Files 1</h2>
<span class="btn btn-default btn-file">
Browse <input data-bind="event: {change: FileGroup1.fileUpload}" type="file" />
</span>
<br />
<div class="fileList" data-bind="foreach: FileGroup1.files">
<span data-bind="text: name"></span>
<a href="#" data-bind="click: $parent.removeFile">Remove</a>
<br />
</div>
</div>
在 https://jsfiddle.net/alexjamesbrown/aw0798p7/
我做错了吗$parent.removeFile
-似乎点击时不会被调用吗?
Am I wrong to do $parent.removeFile
- it seems this doesn't get called on click?
这是一个简化的示例,而不是成品!
This is a cut down working example, not the finished product!
推荐答案
您误会了$parent
.它带出了一个上下文级别.您的foreach
使用FileGroup1.files
作为其索引,因此您可能会认为$parent
级别将是Filegroup1
,但事实并非如此.这是顶级视图模型,因为这是foreach
之外的上下文.
You're misunderstanding $parent
. It takes you out one context level. Your foreach
uses FileGroup1.files
as its index, so you might think that the $parent
level would be Filegroup1
, but it's not. It's the top-level viewmodel, because that is the context outside the foreach
.
所以您的click
绑定应该是
click: $parent.FileGroup1.removeFile
这篇关于未绑定到foreach中的单击动作的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!