Function bound to click action in foreach not being called

筅森魡賤 提交于 2020-01-05 09:46:46

问题


I'm having trouble binding my click action to the view model function to remove an item from an array (inside a foreach binding)

I've got the following view model

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);

And my view, which basically lists 3 "groups" of buttons, where a user can select files to upload

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>

Fiddle at https://jsfiddle.net/alexjamesbrown/aw0798p7/

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!


回答1:


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.

So your click binding should be

click: $parent.FileGroup1.removeFile


来源:https://stackoverflow.com/questions/33392198/function-bound-to-click-action-in-foreach-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!