Wondermoose
Wondermoose

Reputation: 311

Passing values to ko.computed in Knockout JS

I've been working for a bit with MVC4 SPA, with knockoutJs,

My problem is I want to pass a value to a 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. The function is being called, but Id is undefined (I've tried with 'Firm' as well), if I change:

var filter = id;     TO      var filter = 1;

It works fine,

So... How do you pass a value to a ko.computed? It doesn't need to be the Id, it can also be the Firm object etc.

Upvotes: 15

Views: 19082

Answers (2)

Jason Goemaat
Jason Goemaat

Reputation: 29234

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:

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

Upvotes: 19

Rene Pot
Rene Pot

Reputation: 24815

Knockout doesn't allow you pass anything to a computed function. 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.

Upvotes: 8

Related Questions