我暂时没有使用Knockout,并且在尝试将表单字段的输入值修剪为两位小数时遇到了问题。我创建了下面计算的observable,并通过我想用修剪值更新的observable订阅它。谁能告诉我我做错了什么?
查看模型
function createViewModel() {
var self = {};
self.SalesRepId = ko.observable().extend({ required: true });
self.PriceAdvanced = ko.observable("").extend({ required: true, min: 1, max: 200 });
self.decimalValue = ko.computed(function () {
var num = self.PriceAdvanced().slice(0, (self.PriceAdvanced().indexOf(".")) + 3);
return num;
}).extend({ notify: "always" });
self.PriceAdvanced.subscribe(self.decimalValue);
return self;
}
HTML:
<div class="form-group col-xs-12">
<label class="label-col col-xs-4 control-label labelFormat" for="PriceAdvanced"><span class="warn">* </span>Advanced Criminal History Search</label>
<div class="col-xs-8">
<input class="form-control max225" type="text" id="PriceAdvanced" name="PriceAdvanced" data-bind="textInput: PriceAdvanced" size="23" placeholder="$0.00" />
</div>
</div>
答案 0 :(得分:1)
ko.applyBindings
方法?如果没有,您需要在代码末尾调用它。decimalValue
将小数位数限制为2,然后PriceAdvanced
会订阅decimalValue
的更新值,对吧?但是订阅并不是那样的。计算的observables监听它们内部的observable,.subscribe
函数是observable本身的监听器。所以你的代码将处于永无止境的循环中。另外我想你只想限制小数位,而不是数字本身对吗?因此,只有存在小数点时,才更改代码以修剪值。
function createViewModel() {
var self = {};
self.SalesRepId = ko.observable().extend({ required: true });
self.PriceAdvanced = ko.observable("").extend({ required: true, min: 1, max: 200 });
self.decimalValue = ko.computed(function () {
var num = self.PriceAdvanced().indexOf(".") > -1? self.PriceAdvanced().slice(0, (self.PriceAdvanced().indexOf(".")+3)): self.PriceAdvanced();
//return num;
self.PriceAdvanced(num);
}).extend({ notify: "always" });
return self;
}
ko.applyBindings(new createViewModel());
注意:您的扩展程序min: 1
,max: 200
将无效,因为PriceAdvanced
包含字符串而不是数字。