简体   繁体   中英

Knockout Computed Observable with parameters

Is it possible to provide a computed observable an extra parameter?

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:

<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.

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. However, if firstName eg changes, fullName will NOT be updated because fullName is a function without subscribers.

You could use another observable for seperator and use this observable in the computed fullName. Then fullName WILL be updated when either firstName, seperator or lastName changes.

But that will not work in the original scenario either. Looking for an answer myself...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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