简体   繁体   English

将值传递给Knockout JS中的ko.computed

[英]Passing values to ko.computed in Knockout JS

I've been working for a bit with MVC4 SPA, with knockoutJs, 我一直在使用MVC4 SPA工作,有敲门声,

My problem is I want to pass a value to a ko.computed. 我的问题是我想将值传递给ko.computed。 Here is my code. 这是我的代码。

<div data-bind="foreach: firms">
<fieldset>
    <legend><span data-bind="text: Name"></span></legend>
    <div data-bind="foreach: $parent.getClients">
        <p>
            <span data-bind="text: Name"></span>
        </p>
    </div>
</fieldset>
</div>

self.getClients = ko.computed(function (Id) {
    var filter = Id;
    return ko.utils.arrayFilter(self.Clients(), function (item) {
        var fId = item.FirmId();
        return (fId === filter);
    });
});

I simply want to display the Firmname as a header, then show the clients below it. 我只想将Firmname显示为标题,然后显示它下面的客户端。 The function is being called, but Id is undefined (I've tried with 'Firm' as well), if I change: 正在调用该函数,但Id未定义(我也尝试使用'Firm'),如果我改变:

var filter = id;     TO      var filter = 1;

It works fine, 它工作正常,

So... How do you pass a value to a ko.computed? 那么......你如何将值传递给ko.computed? It doesn't need to be the Id, it can also be the Firm object etc. 它不需要是Id,它也可以是Firm对象等。

Each firm really should be containing a list of clients, but you could use a regular function I think and pass it the firm: 每个公司真的应该包含一个客户列表,但你可以使用我认为的常规功能并将其传递给公司:

self.getClientsForFirm = function (firm) {
    return ko.utils.arrayFilter(self.Clients(), function (item) {
        var fId = item.FirmId();
        return (fId === firm.Id());
    });
});

Then in html, $data is the current model, in your case the firm: 然后在html中,$ data是当前模型,在您的情况下是公司:

<div data-bind="foreach: $root.getClientsForFirm($data)">

Knockout doesn't allow you pass anything to a computed function. Knockout不允许您将任何内容传递给计算函数。 That is not what it is for. 这不是它的用途。 You could instead just use a regular function there if you'd like. 如果你愿意,你可以在那里使用常规功能。

Another option is to have the data already in the dataset on which you did the first foreach. 另一种选择是将数据存储在您第一次执行的数据集中。 This way, you don't use $parent.getClients , but more like $data.clients . 这样,您不使用$parent.getClients ,而更像$data.clients

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM