简体   繁体   English

带参数的 Knockout Computed Observable

[英]Knockout Computed Observable with parameters

Is it possible to provide a computed observable an extra parameter?是否可以为计算出的 observable 提供一个额外的参数?

For example, something like this:例如,这样的事情:

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    var self = this;
    this.fullName = ko.computed(function(separator) {
       return self.firstName() + ' ' + self.lastName();
    }, this);
};

And then in the html:然后在html中:

<div data-bind="text: fullName(' - ')"></div>

My actual use case is far more complicated, but this is essentially what I'm trying to achieve, pass in a value in the html which is used as part of the computed function.我的实际用例要复杂得多,但这基本上是我想要实现的,在 html 中传递一个值,该值用作计算函数的一部分。

Failing this is there a way to make a ordinary function which takes parameters behave like a (computed) observable?如果做不到这一点,有没有办法让普通函数接受参数的行为就像一个(计算的)可观察对象?

You can create a function, which returns an computed variable.您可以创建一个函数,它返回一个计算变量。 You can try something like this.你可以尝试这样的事情。

var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    var self = this;
    this.fullName = function(separator){
    return ko.computed(function () {
            return self.firstName() + separator + self.lastName();}, this);
};
};

<div data-bind="text: ViewModel.fullName('-')"></div>

If the viewModel is fairly static, this solution might help.如果 viewModel 相当静态,则此解决方案可能会有所帮助。 However, if firstName eg changes, fullName will NOT be updated because fullName is a function without subscribers.但是,如果 firstName 例如更改,则 fullName 将不会更新,因为 fullName 是一个没有订阅者的函数。

You could use another observable for seperator and use this observable in the computed fullName.您可以使用另一个 observable 作为分隔符,并在计算的 fullName 中使用此 observable。 Then fullName WILL be updated when either firstName, seperator or lastName changes.然后 fullName 将在 firstName、separator 或 lastName 更改时更新。

But that will not work in the original scenario either.但这在原始场景中也不起作用。 Looking for an answer myself...自己找答案。。。

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

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