繁体   English   中英

带参数的 Knockout Computed Observable

[英]Knockout Computed Observable with parameters

是否可以为计算出的 observable 提供一个额外的参数?

例如,这样的事情:

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);
};

然后在html中:

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

我的实际用例要复杂得多,但这基本上是我想要实现的,在 html 中传递一个值,该值用作计算函数的一部分。

如果做不到这一点,有没有办法让普通函数接受参数的行为就像一个(计算的)可观察对象?

您可以创建一个函数,它返回一个计算变量。 你可以尝试这样的事情。

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>

如果 viewModel 相当静态,则此解决方案可能会有所帮助。 但是,如果 firstName 例如更改,则 fullName 将不会更新,因为 fullName 是一个没有订阅者的函数。

您可以使用另一个 observable 作为分隔符,并在计算的 fullName 中使用此 observable。 然后 fullName 将在 firstName、separator 或 lastName 更改时更新。

但这在原始场景中也不起作用。 自己找答案。。。

暂无
暂无

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

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