是否可以为计算的可观察对象提供额外的参数?
例如,像这样:
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>
关于javascript - 带参数的 Knockout Computed Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24278107/