javascript 在 Knockout JS 中将值传递给 ko.computed
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10822873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing values to ko.computed in Knockout JS
提问by Wondermoose
I've been working for a bit with MVC4 SPA, with knockoutJs,
我一直在使用 MVC4 SPA,使用 KnockoutJs,
My problem is I want to pass a value to a ko.computed. Here is my code.
我的问题是我想将一个值传递给 ko.computed。这是我的代码。
<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:
我只想将 Firmname 显示为标题,然后显示其下方的客户端。正在调用该函数,但 Id 未定义(我也尝试过使用“Firm”),如果我更改:
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.
那么......你如何将值传递给 ko.computed?它不需要是 Id,也可以是 Firm 对象等。
回答by Jason Goemaat
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)">
回答by Rene Pot
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.
Knockout 不允许您将任何内容传递给计算函数。那不是它的用途。如果您愿意,您可以改为在那里使用常规函数。
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
.
另一种选择是让数据已经存在于您执行第一个 foreach 的数据集中。这样,您就不会使用$parent.getClients
,而更像是$data.clients
。