Knockoutjs:如何将单个项目从可观察数组传递到我的视图模型中

Knockoutjs: How can I pass a single item from an observable array into my viewmodel?

本文关键字:数组 我的 模型 视图 观察 单个 项目 Knockoutjs      更新时间:2023-09-26

我正在KnockoutJS中创建一个错误处理程序,但我遇到了一个问题。我的主页上有一个"错误"报告列表,该列表使用可观察数组显示。当我在列表中的错误报告之一上单击"查看"时,我有一个引导模式弹出窗口。我想用报告详细信息填充模式的内容,但由于某种原因,视图模型没有正确传入。

这是我的视图模型,以及下面的ajax映射:

    function BugsViewModel(doJSON) { //doJSON determines whether to populate the observable with JSON or leave it empty
        var self = this;
        self.bugs = ko.observableArray();
        self.removeBug = function (bug) {
            $.ajax({
                url: "/ajax/getbugs.ashx?deleteBug=" + bug.Id()
            })
            self.bugs.remove(bug);
        }
        self.currentBug = ko.observable(); // <--this is the bug that I want to reference in the modal
        self.setModalBug = function (obj, event) { //obj is the individual array item
            self.currentBug = obj; //setting currentBug so that I can use it in my view
            alert(self.currentBug.Id()); //<--these alert properly, so I know that the value I'm passing in (obj) is correct
            alert(self.currentBug.BugName());
        }
        if(doJSON)
            getViewModelJSON(self.bugs); //this function loads my array (self.bugs) with observable items
    }
function getViewModelJSON(model) {
        $.ajax({
            url: "/ajax/getbugs.ashx"
        })
    .done(function (data) {
        ko.mapping.fromJSON(data, {}, model);
    });
    }
    $(document).ready(function () {
        viewModel = new BugsViewModel(true);
        ko.applyBindings(viewModel);
    });

我有我的"查看"按钮,它调用"setModalBug"并打开模态:

<a href="#" class="btn btn-default" data-toggle="modal" data-target="#bugDetails" data-id="value: Id" data-bind="click: $root.setModalBug">View</a>

然后,在我的详细信息模态中,我有一个要填充数据的文本框。这就是我遇到问题的地方 - currentBug.BugName 没有正确填充值。

<input type="text" id="txtBugName" data-bind="textInput: currentBug.BugName" />

(请注意,我正在使用Mapping插件进行Knockout,因此即使您没有在我的视图modal中看到定义的"BugName",当我调用"ko.mapping.fromJSON()"时,它是从JSON生成的。

我有点困惑。这是运行时问题,还是我不正确地调用视图模型?还是完全不同的东西?

谢谢

您没有正确地将值分配给可观察量。 您正在执行的操作:

self.currentBug = ko.observable();
self.currentBug = obj;

第一行创建一个可观察量,但第二行将其丢弃并替换为 bug 对象。 您希望分配给可观察量,而不是将其丢弃,例如:

self.currentBug = ko.observable();
self.setModalBug = function (obj, event) {
    self.currentBug(obj); //<-- Assign the current bug the currentBug observable
    alert(self.currentBug().Id()); //note the additional () to read the value of the observable
    alert(self.currentBug().BugName());
}

我让它工作了。显然,在我的代码中,我实际上没有在我的警报中添加额外的"()"。 对不起——不是我最好的时刻。现在它可以工作:

self.currentBug(obj);
alert(self.currentBug().Id());
alert(self.currentBug().BugName());

然后我在文本输入数据绑定中添加了一个额外的"()":

<input type="text" id="txtBugName" data-bind="textInput: currentBug().BugName" />

我没有意识到我必须在数据绑定的任何地方使用"()"。我认为它发现您正在使用可观察量并以这种方式处理它(它在属性"BugName"上确实如此,但我必须在末尾使用"()"访问当前错误)。

谢谢,雷萨姆!我花了很多时间在这上面,这越来越令人沮丧。事实证明,这是一个非常简单的修复。