Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 621
Wondermoose Avatar asked May 30 '12 19:05

Wondermoose


People also ask

What is Ko computed in KnockoutJS?

ko. computed( evaluator [, targetObject, options] ) — This form supports the most common case of creating a computed observable. evaluator — A function that is used to evaluate the computed observable's current value. targetObject — If given, defines the value of this whenever KO invokes your callback functions.

How do you bind data in KnockoutJS?

Binding syntax The binding name should generally match a registered binding (either built-in or custom) or be a parameter for another binding. If the name matches neither of those, Knockout will ignore it (without any error or warning). So if a binding doesn't appear to work, first check that the name is correct.

How does Ko computed work?

Whenever you declare a computed observable, KO immediately invokes its evaluator function to get its initial value. While the evaluator function is running, KO sets up a subscription to any observables (including other computed observables) that the evaluator reads.


1 Answers

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)">
like image 132
Jason Goemaat Avatar answered Oct 24 '22 01:10

Jason Goemaat