计算的可观察动态变量

时间:2012-11-20 21:35:40

标签: javascript knockout.js computed-observable

我有一个输入字段,当selectbox更改它的值时,应该动态填充该字段。因此,我将变量绑定到输入,将另一个值绑定到选择框的选定值。现在我希望能够以编程方式更改输入值:对于selectbox的某些值,值应为空字符串,而对于其他值,我应该在用户执行某些操作时使用一些javascript代码设置它。我虽然使用了一个计算函数,所以我可以返回空字符串,但这会导致我遇到一个问题:如何在选择其他选择框选项时以编程方式设置值?

1 个答案:

答案 0 :(得分:1)

如果您的目标是在input更改时select中的值默认并允许用户自由更新,那么一个不错的选择就是使用manual subscription

var ViewModel = function() {
   this.selectedValue = ko.observable();
   this.otherValue = ko.observable();

   this.selectedValue.subscribe(function(newValue) {
       //perform whatever logic that you need to determine how the other value should be populated based on the dropdown's current value (newValue)
       this.otherValue(calculatedValue);
   }, this);
};
相关问题